JavaScript 图片压缩的原理主要基于以下几个方面:
一、基本概念
二、优势
三、类型
四、应用场景
五、压缩原理
六、示例代码(前端使用 canvas 进行简单压缩)
function compressImage(file, maxWidth = 800, quality = 0.7) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(event) {
const img = new Image();
img.src = event.target.result;
img.onload = function() {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxWidth) {
width *= maxWidth / height;
height = maxWidth;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
resolve(blob);
}, 'image/jpeg', quality);
};
img.onerror = reject;
};
reader.onerror = reject;
});
}
七、常见问题及解决方法
总之,JavaScript 图片压缩是一个综合考虑多种因素的过程,需要根据具体需求进行调整和优化。
没有搜到相关的文章