图片缩略图

function resizeImage(src,callback,w,h){

     var canvas = document.createElement("canvas"),
         ctx = canvas.getContext("2d"),
         im = new Image();
         w = w || 0,
         h = h || 0;
     im.onload = function(){
         //为传入缩放尺寸用原尺寸
         !w && (w = this.width);
         !h && (h = this.height);
         //以长宽最大值作为最终生成图片的依据
         if(w !== this.width || h !== this.height){
             var ratio;
             if(w>h){
                 ratio = this.width / w;
                 h = this.height / ratio;
             }else if(w===h){
                 if(this.width>this.height){
                     ratio = this.width / w;
                     h = this.height / ratio;
                 }else{
                     ratio = this.height / h;
                     w = this.width / ratio;
                 }
             }else{
                 ratio = this.height / h;
                 w = this.width / ratio;
             }
         }
         //以传入的长宽作为最终生成图片的尺寸
         if(w>h){
             var offset = (w - h) / 2;
             canvas.width = canvas.height = w;
             ctx.drawImage(im,0,offset,w,h);
         }else if(w<h){
             var offset = (h - w) / 2;
             canvas.width = canvas.height = h;
             ctx.drawImage(im,offset,0,w,h);
         }else{
             canvas.width = canvas.height = h;
             ctx.drawImage(im,0,0,w,h);
         }
         callback(canvas.toDataURL("image/png"));
     }
     im.src = src;
}

转载于:https://www.cnblogs.com/hy-l92/p/11101318.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值