/**
|
* @description: 图片压缩
|
* @param {*} src 图片地址
|
* @param {*} quality 压缩质量
|
* @param {*} maxWidth 最大宽度
|
* @param {*} callback 回调函数
|
* @return {*}
|
*/
|
function compressImage(src, quality, maxWidth, callback) {
|
const img = new Image();
|
img.setAttribute('crossOrigin', 'Anonymous');
|
img.onload = function () {
|
const canvas = document.createElement('canvas');
|
const ctx = canvas.getContext('2d');
|
let width = img.width;
|
let height = img.height;
|
|
if (width > maxWidth) {
|
height *= maxWidth / width;
|
width = maxWidth;
|
}
|
|
canvas.width = width;
|
canvas.height = height;
|
ctx.drawImage(img, 0, 0, width, height);
|
|
const newData = canvas.toDataURL('image/jpeg', quality);
|
// 使用atob()将base64转换为二进制字符串
|
const binaryString = window.atob(newData.split(',')[1]);
|
const mimeString = newData.split(',')[0].split(':')[1].split(';')[0];
|
// 创建Blob对象
|
const array = [];
|
for (let i = 0; i < binaryString.length; i++) {
|
array.push(binaryString.charCodeAt(i));
|
}
|
const blob = new Blob([new Uint8Array(array)], { type: mimeString });
|
|
callback(blob);
|
};
|
img.src = src;
|
|
return src;
|
}
|
|
export default function imageCompress(src, quality, maxWidth) {
|
// 使用例子
|
return compressImage(src, quality, maxWidth, function (blob) {
|
// 创建一个新的图片URL
|
const imageUrl = URL.createObjectURL(blob);
|
// 可以在这里使用imageUrl,比如设置为img元素的src
|
// document.getElementById('your-image-element').src = imageUrl;
|
// 当不需要这个URL的时候,释放它
|
URL.revokeObjectURL(imageUrl);
|
});
|
}
|