使用H5canvas实现图片压缩
用于移动端图片上传,由于现在手机拍的照片动辄几M,如果直接上传速度慢也没有必要,这里利用H5 canvas实现图片压缩
基本原理是通过canvas渲染图片,再通过 toDataURL 方法压缩保存为base64字符串(能够编译为jpg格式的图片)
// 利用canvas压缩图片,传入四个参数,分别是data:获取到的文件,w, h 要压缩的宽高, 和一个回调函数将获取到的压缩文件传递出去
canvasCompressPic(data, w, h, callback) {
let newImg = new Image();
newImg.src = data;
let imgWidth, imgHeight;
newImg.onload = () => {
let img = document.createElement('img');
img.src = newImg.src;
imgWidth = img.width;
imgHeight = img.height;
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
if (imgWidth > imgHeight) {
imgWidth = w * imgWidth / imgHeight;
imgHeight = h;
} else {
imgHeight = h * imgHeight / imgWidth;
imgWidth = w;
};
canvas.width = imgWidth;
canvas.height = imgHeight;
ctx.clearRect(0, 0, w, h);
// 处理png格式图片背景变黑的问题
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
let rate = 0.7;
let base64 = canvas.toDataURL('image/jpeg', rate);
callback(base64);
};
}