1234

js压缩图片

1.js

/*canvas压缩图片
   *width:压缩后宽度
   *height:压缩后高度
   *img:img dom对象
   */
    function compressImg(width, height, img) {
        var canvas = document.createElement('canvas'), c = canvas.getContext('2d');
        canvas.width = width;
        canvas.height = height;
        c.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, width, height);
        return canvas.toDataURL('image/png');
    }

2.按比例压缩调用方式

var img = new Image();
img.src = reader.result;
img.onload = function () {
var w = this.width,
h = this.height,
scale = w / h;
//压缩图片
var b64 = compressImg(600, 600 / scale, img);
}

 

 

posted @ 2019-11-25 16:23  法杨  阅读(1068)  评论(0)    收藏  举报