USharing
开放博客

通过js将base64图片进行压缩

直接上代码:

/* 压缩base64图片,怎么压缩base64是题外话,这里不赘述 */
function compress(
    base64,        // 源图片
    rate,          // 缩放比例
    callback       // 回调
) {
    //处理缩放,转格式
    var _img = new Image();
    _img.src = base64;
    _img.onload = function() {
        var _canvas = document.createElement("canvas");
        var w = this.width / rate;
        var h = this.height / rate;
        _canvas.setAttribute("width", w);
        _canvas.setAttribute("height", h);
        _canvas.getContext("2d").drawImage(this, 0, 0, w, h);
        var base64 = _canvas.toDataURL("image/jpeg");
        _canvas.toBlob(function(blob) {
            if(blob.size > 750*1334){        //如果还大,继续压缩
                compress(base64, rate, callback);
            }else{
                callback(base64);
            }
        }, "image/jpeg");
    }
}


compress(
    "data:image/jgp;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7SPYUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAA0scAVoAAxslRxwBWgADGyVHHA",
    1.5,
    function(base64){
        console.log(base64);
    }
)

 

来源:https://juejin.im/post/5dce4ccef265da0bad797a50

赞(0) 打赏
未经允许不得转载:USharing » 通过js将base64图片进行压缩

觉得文章有用就打赏一下文章作者

微信扫一扫打赏