前端對圖片壓縮處理
阿新 • • 發佈:2022-05-07
//第一個引數就是原來的字串,第二個是寬度,第三個就是回撥方法
export const cutImageBase64=(base64, w, callback)=> {
let newImage = new Image();
let quality = 0.6; //壓縮係數0-1之間
newImage.src = base64;
newImage.setAttribute("crossOrigin", 'Anonymous'); //url為外域時需要
let imgWidth, imgHeight;
newImage.onload = function () {
imgWidth = this.width;
imgHeight = this.height;
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w;
canvas.height = w * imgHeight / imgWidth;
} else {
canvas.height = w;
canvas.width = w * imgWidth / imgHeight;
}
} else {
canvas.width = imgWidth;
canvas.height = imgHeight;
quality = 0.6;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
let base64 = canvas.toDataURL("image/jpeg", quality); //壓縮語句
// 如想確保圖片壓縮到自己想要的尺寸,如要求在50-150kb之間,請加以下語句,quality初始值根據情況自定
while (base64.length / 1024 > 150) {
quality -= 0.01;
base64 = canvas.toDataURL("image/jpeg", quality);
}
// 防止最後一次壓縮低於最低尺寸,只要quality遞減合理,無需考慮
while (base64.length / 1024 < 50) {
quality += 0.001;
base64 = canvas.toDataURL("image/jpeg", quality);
}
callback(base64);//必須通過回撥函式返回,否則無法及時拿到該值
}
}