对上传的图片进行压缩,须要借助于canvas API,调用其中的canvas.toDataURL(type, encoderOptions); 将图片按照必定的压缩比进行压缩,获得base64编码。重点来了:压缩策略:先设置图片的最大宽度 or 最大高度,通常设置其中一个就能够了,由于全部的手机宽高比差异不是很大。而后设置图片的最大size,allowMaxSize,根据图片的实际大小和最大容许大小,设置相应的压缩比率。前端 //最终实现思路:
一、设置压缩后的最大宽度 or 高度;
二、设置压缩比例,根据图片的不一样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;
}