前端使用js压缩图片上传

后端要求前端上传图片时进行压缩,本文记录js和canvas来压缩图片,时间有点久,忘记原文的地址了

 // 上传图片压缩, 调用此方法返回的blob文件,在FormData.append的时候file字段必须传第三参数为文件名字
  compressImg(file) {
    const _that = this;
    var fileSize = parseFloat(parseInt(file["size"]) / 1024 / 1024).toFixed(2);
    var read = new FileReader();
    read.readAsDataURL(file);
    return new Promise(function(resolve) {
      const type = file.type,
        fileName = file.name;
      read.onload = function(e) {
        const img = new Image();
        img.src = e.target.result;
        img.onload = function() {
          //默认按比例压缩
          let w = this.width > 1440 ? 1400 : this.width,
            h =
              this.width > 1440
                ? 1440 * (this.height / this.width)
                : this.height;
          //生成canvas
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");

          let base64;
          // 创建属性节点
          canvas.setAttribute("width", w);
          canvas.setAttribute("height", h);
          ctx.drawImage(this, 0, 0, w, h);
          // 图像质量
          if (fileSize < 1) {
            //如果图片小于一兆 那么不执行压缩操作
            base64 = canvas.toDataURL(type, 1);
          } else if (fileSize > 1 && fileSize < 2) {
            //如果图片大于1M并且小于2M 那么压缩0.5 | 0.8
            base64 = canvas.toDataURL(type, 0.8);
          } else {
            //如果图片超过2m 那么压缩0.2
            base64 = canvas.toDataURL("image/jpeg", 0.2);
          }
          // 可兼容ie转blob
          let f = _that.base64URLtoFile(base64, fileName);
          // 不兼容ie转file
          // let file = _that.base64ToFile(base64, fileName);
          resolve(f);
        };
      };
    });
  },

版权声明:本文为m0_47918831原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。