上传图片时候,遇到要上传很大的图片,上传的时候就会很慢。所以,需要对图片进行压缩处理来优化上传功能。
图片压缩函数:
/*
* 图片压缩
* img 原始图片
* width 压缩后的宽度
* height 压缩后的高度
* ratio 压缩比率
*/
function compress(img, width, height, ratio) {
var canvas, ctx, img64;
canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
img64 = canvas.toDataURL("image/jpeg", ratio);
return img64;
}
图片压缩函数,返回 base64 格式的图片数据。 其中压缩比率ratio取值(0 - 1 之间),ratio越大图片质量越高。
这里将图片转为 jpeg格式,因为转为 png 格式的话,图片的 base64 比转为 jpeg 的要长不少。
<input type="file" accept="image/*" name="imageFile" @change="upload">
上传图片后 @change绑定的upload 函数将被触