可以使用HTML5的Canvas元素和JavaScript来实现图片压缩。具体步骤如下:
- 将图片读取到一个Image对象中。
- 创建一个Canvas元素并将图片绘制到其中。
- 获取Canvas元素上的图像数据,并进行压缩处理。
- 将压缩后的图像数据重新绘制到Canvas元素中。
- 将Canvas元素中的图像转换为压缩后的Base64编码字符串或Blob对象。
以下是一个基本的示例代码:
function compressImage(file, maxWidth, maxHeight) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(
blob => {
resolve(blob);
},
file.type,
0.8 // 压缩质量,可以根据需要调整
);
};
img.onerror = reject;
img.src = URL.createObjectURL(file);
});
}
这个函数接收一个File对象、最大宽度和最大高度作为参数,并返回一个Promise对象,该Promise对象在图片压缩完成后解析为Blob对象。可以使用这个函数来实现图片上传前的压缩处理。