图片压缩
核心压缩函数
javascript
// 核心压缩函数
function compressImage(file, options) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
// 创建Canvas元素
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 计算调整后的尺寸
let { width, height } = img;
if (width > options.maxWidth || height > options.maxHeight) {
const ratio = Math.min(
options.maxWidth / width,
options.maxHeight / height
);
width = Math.floor(width * ratio);
height = Math.floor(height * ratio);
}
// 设置Canvas尺寸
canvas.width = width;
canvas.height = height;
// 绘制图片到Canvas
ctx.drawImage(img, 0, 0, width, height);
// 转换为Blob
canvas.toBlob(
(blob) => {
if (!blob) return reject(new Error('压缩失败'));
resolve(blob);
},
'image/jpeg', // 输出格式
options.quality // 压缩质量
);
};
img.onerror = reject;
img.src = URL.createObjectURL(file);
});
}