function dealImage (base64,w) {
//壓縮base64方法
var newImage = new Image();
var quality = 0.6; //壓縮系數0-1之間
newImage.src = base64;
newImage.setAttribute(“crossOrigin”, ‘Anonymous’); //url為外域時需要
var imgWidth, imgHeight;
newImage.onload = function () {
imgWidth = this.width;
imgHeight = this.height;
var canvas = document.createElement(“canvas”);
var 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);
var base64 = canvas.toDataURL(“image/jpeg/*”, quality); //壓縮語句
console.log(base64);
return base64;
}
},
使用的時候直接調用該函數:dealImage (”這個傳遞汲取一個圖檔base64“,”這個傳遞圖檔寬度我一般傳1000“);函數會将壓縮過的base64直接傳回出來