图片上传自动压缩方案
作者:互联网
compressor.js
结合Antd或者Element等Upload组件的BeforeUpload动作,对Blob数据进行处理,基于canvas,因此需要判断透明,非透明的直接转换为jpg,获取最优压缩比例;透明的直接压缩,输出前需要判断图片压缩大小,防止返回变大的图片
import Compressor from 'compressorjs'
async beforeUpload(file: Blob) {
const curSize = file.size
const dataURL = await filetoDataURL(file)
const image = await dataURLtoImage(dataURL)
const cvs = document.createElement('canvas')
const ctx = cvs.getContext('2d')
let isAlphaBackground = false
if (ctx) {
ctx.clearRect(0, 0, cvs.width, cvs.height)
ctx.drawImage(image, 0, 0)
const imageData = ctx.getImageData(0, 0, cvs.width, cvs.height).data
// 检测有没有透明数据
for (let index = 3; index < imageData.length; index += 4) {
if (imageData[index] != 255) {
isAlphaBackground = true
break
}
}
}
if (this.compress) {
return new Promise((resolve, reject) => {
new Compressor(file, {
quality: 0.9,
convertSize: isAlphaBackground ? undefined : 1000,
success(result) {
console.log(result.size)
const finalFile = result.size > file.size ? file : result
resolve(finalFile)
},
error(error) {
console.error(error)
reject(error)
}
})
})
}
}
标签:const,压缩,ctx,cvs,自动,result,file,error,上传 来源: https://blog.csdn.net/Kobe_G/article/details/120486003