码迷,mamicode.com
首页 > Web开发 > 详细

js compress 图片

时间:2016-05-16 20:08:45      阅读:201      评论:0      收藏:0      [点我收藏+]

标签: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();
    };



}


js compress 图片

标签:web   html   javascript   image   compress   

原文地址:http://antlove.blog.51cto.com/10057557/1774019

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!