标签:web html javascript image compress
function compressImage(maxWidth,maxHeight,srcOriginalImage,callback){ // 创建 canvas var canvasId ="canvas_"+new Date().getTime()+""+parseInt(Math.random()); $("<canvas></canvas>").hide().attr("id",canvasId).appendTo("body"); var c=$("#"+canvasId)[0]; var ctx=c.getContext("2d"); // 释放canvas function releaseCanvas(){ $("#"+canvasId).remove(); } // 创建要绘制的Image对象 var img = new Image(); img.src = srcOriginalImage; // 等待img加载完毕 img.onload = function(){ // 与backgournd-size:contain效果相同 if(img.width/img.height<maxWidth/maxHeight){ c.height = img.height; if(img.height>maxHeight){ c.height = maxHeight; } c.width = img.width/img.height*c.height; }else{ c.width = img.width; if(img.width>maxWidth){ c.width = maxWidth; } c.height = img.height/img.width*c.width; } ctx.drawImage(img,0,0,img.width,img.height,0,0,c.width,c.height); callback(c.toDataURL()); releaseCanvas(); }; }
标签:web html javascript image compress
原文地址:http://antlove.blog.51cto.com/10057557/1774019