前端图片压缩

function dataURItoBlob(dataURI, type) {
      //atob() 方法用于解码使用 base-64 编码的字符串。
      var binary = atob(dataURI.split(",")[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
       // charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。
        array.push(binary.charCodeAt(i));
      }
      //Blob 对象表示一个不可变、原始数据的类文件对象
      return new Blob([new Uint8Array(array)], { type: type });
    },
function  beforeUploadArtImg(file) {
      if(file.type === "image/gif"){
        return true;
      }
      const _this = this;
      return new Promise(resolve => {
        //FileReader读取到文件中的数据
        const reader = new FileReader();
        const image = new Image();
        // 最大尺寸限制,可通过设置宽高来实现图片压缩程度
        let maxWidth = 600, maxHeight = 600;
        image.onload = imageEvent => {
          const canvas = document.createElement("canvas");
          const context = canvas.getContext("2d");
          const originWidth = image.width ;
          const originHeight = image.height;

          let targetWidth = originWidth,
              targetHeight = originHeight;

          // 图片尺寸超过400x500的限制
          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));
              }
          }

          // canvas对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;

          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 用image 绘制 canvas
          context.drawImage(image, 0, 0, targetWidth, targetHeight);
          
          const dataUrl = canvas.toDataURL(file.type);
          //binary large object
          const blobData = dataURItoBlob(dataUrl, file.type);
          //File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件
          resolve(blobData);
        };
        reader.onload = e => {
          image.src = e.target.result;
        };
        //读取文件内容,结果用data:url的字符串形式表示
        reader.readAsDataURL(file);
      });
    },

npm 包地址 :https://www.npmjs.com/package/canvas-image-compression
gitHub地址:https://github.com/LXJSQ/canvas-image-compression

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值