/**
* @description: base64图片压缩
* @param {file} file类型文件
* @param {maxSizeKB} 最大压缩多少kb
* @return {*}
*/
function compress(file,maxSizeKB){
let Base64URL=''
if (file.size > maxSizeKB * 1024) {
let rate = 0 // 压缩率
// 文件转图片
const dataUrl = await fileToImgAsync(file)
// // 图片转画布
const image= await loadImageAsync(dataUrl)
// 文件大小KB, file.size给的是字节Byte
const fileSizeKB = file.size / 1024
// 当图片大小超标,才进行压缩
if (fileSizeKB > maxSizeKB) {
// 计算压缩率
rate = (fileSizeKB - maxSizeKB) / fileSizeKB
console.log('压缩率:', rate)
console.log('压缩后文件大小:', fileSizeKB * (1 - rate), 'kb')
}
// 纠正因子,不加会导致压缩出的文件太小
const factor = 0.2
// 画布执行压缩
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const cvWidth = image.width * (1 - rate + factor)
const cvHeight = image.height * (1 - rate + factor)
canvas.height = cvHeight
canvas.width = cvWidth
context?.clearRect(0, 0, cvWidth, cvHeight)
context?.drawImage(image, 0, 0, cvWidth, cvHeight)
Base64URL = canvas.toDataURL('image/jpeg', 0.7)
// console.log(Base64URL, '---------Base64URL---------')
// return Base64URL
}
return Base64URL
}
// // 异步读取图片的promise
function loadImageAsync (url) {
return new Promise(function (resolve, reject) {
//new imag内不可以传url 或者 宽度拿不到
const image = new Image()
image.src = url
image.onload = function () {
resolve(image)
};
image.onerror = function () {
reject(new Error('Could not load image at ' + url))
};
})
}
// // 异步转换成base64编码的promise
function fileToImgAsync (file) {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
reader.onload =e=>{
resolve(e.target.result);
};
reader.onerror = function () {
reject(new Error('readAsDataURL:fail'))
};
reader.readAsDataURL(file)
});
}
react写法 参考https://www.cnblogs.com/ww01/p/13328664.html