将图片压缩 --base64转文件

    compressImg(file) {
      console.log("compressImg============file",file)
        let fileName = file.file.name;
        // maxSize 是压缩的设置,设置图片的最大宽度和最大高度,等比缩放,level 质量,数值越小质量越低
        let maxSize = { width: 1000, height: 1000, level: 0.8 };
        let _this = this;
        let newFile = file.file;
        let reader = new FileReader();
        reader.readAsDataURL(newFile);

        reader.onload = function(event) {
          console.log("event.target.result",event);
          let IMG = new Image();
          IMG.src = event.target.result;
          let imgWidth = 0,imgHeight = 0;
          IMG.onload = function() {
              let w = this.naturalWidth,
                h = this.naturalHeight;
              if (w > maxSize.width || h > maxSize.height) {
               let multiple = Math.max(w / maxSize.width, h / maxSize.height);
              imgWidth = w / multiple;
              imgHeight = h / multiple;
              let canvas = document.createElement('canvas'),
                ctx = canvas.getContext('2d');
              canvas.width = imgWidth;
              canvas.height = imgHeight;
              ctx.drawImage(this, 0, 0, imgWidth, imgHeight);
              let base64 = canvas.toDataURL('image/jpeg', maxSize.level || 1); 
              _this.imgFile.file = _this.dataURLtoFile(base64, fileName);
            } else {
              _this.imgFile.file = file.file;
            }
            console.log("_this.formData1=====",_this.imgFile)
          }
        }
    },


    /**
     * base64转文件
     */
    dataURLtoFile(dataurl, filename) {   
      console.log("dataURLtoFile==========",dataurl,filename)
       var arr = dataurl.split(','),
	        mime = arr[0].match(/:(.*?);/)[1],
	        bstr = atob(arr[1]),
	        n = bstr.length,
	        u8arr = new Uint8Array(n);
	    while (n--) {
	        u8arr[n] = bstr.charCodeAt(n);
	    }
      console.log("dataURLtoFile==========return",new File([u8arr], filename, { type: mime }));
	    return new File([u8arr], filename, { type: mime });
    },

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值