base64图片压缩

来源:互联网 发布:php扩展加密 编辑:程序博客网 时间:2024/05/29 13:17
/****压缩走的路线***/
function dealImage(re,w,callback){
var newImage=new Image();
var quality=0.7;
newImage.src=re;
var imgWidth,imgHeight;
newImage.onload=function(){
imgWidth=this.width;
imgHeight=this.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;
quality=0.6;
}
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(this,0,0,canvas.width,canvas.height);
var base64=canvas.toDataURL("image/jpeg",quality);


callback(base64);//必须通过毁掉函数返回,否则无法及时拿到改值


}
}




//使用时
dealImage(e.target.result,800,next);


function next(base64){
//这里写一些业务逻辑,同时把base64赋值给后台接口
}