前端上传图片-预览/压缩/上传进度度(附注释完整代码)

   流程如图所示:


关键压缩算法如下:

//可选选项
var ops = {
    width: 500,  //最大宽
    height: 500,  //最大高
    quality: 0.92,  //压缩质量
    convertType: "dataURL", //dataURL 或者 blob
    fileType: "png", //文件类型
}

/**
 * [compressImg description]
 * @param  {File}   file     [description]
 * @param  {Function} callback [用于后续处理]
 * @param  {Object}   ops      [压缩选项]
 * @return {Undefined}            [description]
 */
function compressImg(file, callback, ops) {
    var maxWidth = ops.width || 500 //最大尺寸
    var maxHeight = ops.height || 500 //最大尺寸
    quality = ops.quality || 0.92

    var reader = new FileReader()
    var img = new Image()

    img.onload = () => {
        //原始尺寸
        var originWidth = img.width;
        var originHeight = img.height;
        //实际尺寸
        var targetWidth = originWidth
        var targetHeight = originHeight;
        // 图片尺寸超过最大的限制
        if (originWidth > maxWidth || originHeight > maxHeight) {
            if (originWidth / originHeight > maxWidth / maxHeight) {
                // 更宽,按照宽度限定尺寸
                targetWidth = maxWidth;
                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
                targetHeight = maxHeight;
                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
        }

        var canvas = document.createElement('canvas');  //创建canvas容器
        var context = canvas.getContext('2d');
        canvas.width = targetWidth   //宽高等于图片宽高
        canvas.height = targetHeight //
        // 清除画布
        context.clearRect(0, 0, targetWidth, targetHeight);
        // 图片压缩
        context.drawImage(img, 0, 0, targetWidth, targetHeight);

        //压缩后传给回调函数
        if (ops.convertType === "dataURL") {
            callback(canvas.toDataURL(), file.name)
        } else if (ops.convertType === "blob") {
            canvas.toBlob(function(blob) {
                callback(blob, file.name)
            }, "image/" + ops.fileType, ops.quality)
        }

    }
    reader.onload = (e) => {
        img.src = e.target.result // 文件base64化,以便获知图片原始尺寸
    }
    reader.onabort = () => console.log('file reading was aborted');
    reader.onerror = () => console.log('file reading has failed');

    //根据MIME类型读取图片
    if (file.type.indexOf("image") !== -1) {
       
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值