利用 canvas 实现压缩图片

/**
 *  nase64Data --> 要压缩的图片base64数据
 *  width --> 宽度
 *  height --> 高度
 *  _callback --> 回调函数
 */
function getCompressImage(base64Data, width, height, _callback) {
    var oldimg = new Image();
    oldimg.src = base64Data;
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    canvas.width = width;
    canvas.height = height;
    oldimg.onload = function() {
        console.log('原始宽:' + oldimg.width + "原始高:" + oldimg.height);
        // 绘制
        context.drawImage(oldimg, 0, 0, width, height);
        // 新的base64数据(压缩后的数据)
        var newBase64 = canvas.toDataURL();
        return _callback(newBase64);
    }
}

 

posted @ 2019-07-12 18:01  追梦滴小蜗牛  阅读(631)  评论(0编辑  收藏  举报