项目中上传头像base64图片太大导致上传时间过长,或者后台奔溃问题,所以前端压缩base64大小解决这个问题
原理使用canvas
进行图片压缩
参数说明:
base64String
:需要压缩的base64图片
w
: 图片的原始图片大小
quality
: 0.7 // 值越小,所绘制出的图像越模糊
示例:
let base64Img = this.compressImg(file.content, 100, 0.7);
base64Img
就是压缩完成后的base64图片
compressImg(base64String, w, quality) {
var getMimeType = function(urlData) {
var arr = urlData.split(",");
var mime = arr[0].match(/:(.*?);/)[1];
return mime;
};
var newImage = new Image();
var imgWidth, imgHeight;
var promise = new Promise(resolve => (newImage.onload = resolve));
newImage.src = base64String;
return promise.then(() => {
imgWidth = newImage.width;
imgHeight = newImage.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;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(newImage, 0, 0, canvas.width, canvas.height);
var base64 = canvas.toDataURL(
getMimeType(base64String),
quality
);
console.log(base64);
return base64;
});
}