图像压缩是指通过减少图像的文件大小来达到降低图像质量的目的。在Web应用程序中,图像压缩是一项重要的优化技术,可以提高页面加载速度,降低带宽消耗。
下面是使用JavaScript实现图像压缩的步骤:
/**
* 将图像压缩到指定大小以下
* @param {File} file - 要压缩的图像文件
* @param {Number} maxWidth - 图像宽度的最大值
* @param {Number} maxHeight - 图像高度的最大值
* @param {Function} callback - 压缩完成后的回调函数,参数为压缩后的Blob对象
*/
function compressImage(file, maxWidth, maxHeight, callback) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(event) {
var img = new Image();
img.src = event.target.result;
img.onload = function() {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var width = img.width;
var height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(function(blob) {
callback(blob);
}, file.type);
};
};
}