对上传的图片进行压缩,需要借助于canvas API,调用其中的canvas.toDataURL(type, encoderOptions); 将图片按照一定的压缩比进行压缩,得到base64编码。重点来了:压缩策略:先设置图片的最大宽度 or 最大高度,一般设置其中一个就可以了,因为所有的手机宽高比差别不是很大。然后设置图片的最大size,allowMaxSize,根据图片的实际大小和最大允许大小,设置相应的压缩比率。 //最终实现思路:
1、设置压缩后的最大宽度 or 高度;
2、设置压缩比例,根据图片的不同size大小,设置不同的压缩比。
function compress(res,fileSize) { //res代表上传的图片,fileSize大小图片的大小
var img = new Image(),
maxW = 640; //设置最大宽度
img.onload = function () {
var cvs = document.createElement( 'canvas'),
ctx = cvs.getContext( '2d');
if(img.width > maxW) {
img.height *= maxW / img.width;
img.width = maxW;
}
cvs.width = img.width;
cvs.height = img.height;
ctx.clearRect(0, 0, cvs.width, cvs.height);
ctx.drawImage(img, 0, 0, img.width, img.height);
var compressRate = getCompressRate(1,fileSize);
var dataUrl = cvs.toDataURL( 'image/jpeg', compressRate);
document.body.appendChild(cvs);
console.log(dataUrl);
}
img.src = res;
}
function getCompressRate(allowMaxSize,fileSize){ //计算压缩比率,size单位为MB
var compressRate = 1;
if(fileSize/allowMaxSize > 4){
compressRate = 0.5;
} else if(fileSize/allowMaxSize >3){
compressRate = 0.6;
} else if(fileSize/allowMaxSize >2){
compressRate = 0.7;
} else if(fileSize > allowMaxSize){
compressRate = 0.8;
} else{
compressRate = 0.9;
}
return compressRate;
}