码迷,mamicode.com
首页 > 其他好文 > 详细

canvas 压缩图片的大小

时间:2018-05-17 11:58:04      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:ack   ref   sha   sign   .com   原因   sed   fun   ima   

使用 signature_pad canvas 库生成的图片太大。但又没有提供方法来压缩。

当然这是根据你canvas的画布大小决定的,某些原因导致我的画布就得是那么大。

随随便便一个图片转化为base64 之后就是200kb-300kb。所以得想办法压缩。

思路就是把生成的base64 图片再一次放入canvas 中 ,然后等比缩小4倍即可。

save () {
    if (this.$refs.signature.isEmpty() === false) {
        // https://github.com/WangShayne/vue-signature
        var png = this.$refs.signature.save();
        this.compressedPicture(png, _ => {
            console.log(_);
        })
    }
},
compressedPicture (url, callback) {
    var canvas = document.createElement(‘canvas‘); 
    var ctx = canvas.getContext(‘2d‘); 
    var img = new Image; 
    img.onload = function(){
        console.log(img.width);
        var width = img.width;
        var height = img.height;
        // 按比例压缩4倍
        var rate = (width < height ? width / height : height / width) / 4;
        canvas.width = width * rate; 
        canvas.height = height * rate; 
        ctx.drawImage(img, 0, 0, width, height, 0, 0, width * rate, height * rate); 
        var dataURL = canvas.toDataURL(‘image/jpeg‘); 
        callback.call(this, dataURL); 
        canvas = null; 
        console.log(dataURL);
    };
    img.src = url
},

 

 

 

canvas 压缩图片的大小

标签:ack   ref   sha   sign   .com   原因   sed   fun   ima   

原文地址:https://www.cnblogs.com/CyLee/p/9049193.html

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