Demo:默认压缩选择的节点图片

This commit is contained in:
街角小林 2025-04-25 09:01:51 +08:00
parent d8df80147d
commit 4de35fca9c
2 changed files with 55 additions and 8 deletions

View File

@ -29,6 +29,8 @@
</template>
<script>
import { compressImage } from '@/utils'
export default {
model: {
prop: 'value',
@ -60,12 +62,12 @@ export default {
},
//
selectImg(file) {
this.file = file
let fr = new FileReader()
fr.readAsDataURL(file)
fr.onload = e => {
this.$emit('change', e.target.result)
async selectImg(file) {
try {
const result = await compressImage(file)
this.$emit('change', result)
} catch (error) {
this.$message.error(error)
}
},
@ -92,7 +94,6 @@ export default {
//
deleteImg() {
this.$emit('change', '')
this.file = null
}
}
}

View File

@ -92,4 +92,50 @@ export const getParentWithClass = (el, className) => {
return getParentWithClass(el.parentNode, className)
}
return null
}
}
// 压缩图片
export const compressImage = (file, options = {}) => {
return new Promise((resolve, reject) => {
const fileType = file.type
let {
maxWidth = 1200,
maxHeight = 1200,
quality = 0.8,
mimeType = ''
} = options
const reader = new FileReader()
reader.onload = event => {
// 不处理gif格式
if (/\/gif$/.test(fileType)) {
return resolve(event.target.result)
}
mimeType = mimeType || fileType
const img = new Image()
img.onload = () => {
// 计算新尺寸,保持宽高比
let width = img.width
let height = img.height
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height)
width = Math.floor(width * ratio)
height = Math.floor(height * ratio)
}
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, width, height)
resolve(canvas.toDataURL(mimeType, quality))
}
img.onerror = function() {
reject(new Error('图片加载失败'))
}
img.src = event.target.result
}
reader.onerror = function() {
reject(new Error('文件读取失败'))
}
reader.readAsDataURL(file)
})
}