基于画布canvas进行图片压缩

【基于画布canvas进行图片压缩 - CSDN App】http://t.csdnimg.cn/JPVM3

vantUi上传压缩案例

注意:

需要等比压缩,否则图片会变形

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

    async clzpAfterRead(file) {
     // 大于2MB的图片都缩小像素上传
      console.log(file.file.size, "2097152");
      //2097152
      if (file.file.size > 2097152) {
        let canvas = document.createElement("canvas"); // 创建Canvas对象(画布)
        let context = canvas.getContext("2d");
        let img = new Image();
        img.src = file.content; // 指定图片的DataURL(图片的base64编码数据)
        img.onload = async () => {
          let width = img.width;
          let height = img.height;
          let maxSize = 1024 * 1024 * 2; // 设置最大尺寸,例如2MB

          // 计算压缩比例
          let ratio = Math.sqrt(maxSize / (width * height * 0.5));
          let newWidth = Math.min(width * ratio, maxSize);
          let newHeight = Math.min(height * ratio, maxSize);
          canvas.width = newWidth;
          canvas.height = newHeight;
          context.drawImage(img, 0, 0, newWidth, newHeight);
          file.content = canvas.toDataURL(file.file.type, 0.92); // 0.92为默认压缩质量
          let files = this.dataURLtoFile(file.content, file.file.name);

          await this.uploadImg(files);
        };
      } else {
        //小于2M直接上传
        await this.uploadImg(file.file);
      }
    },

    //上传
    uploadImg(file) {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("bizBelongTo", this.bizBelongTo);
      apiStoreManagement
        .uploadShopImage(formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          if (res.code == "0000") {
            if (file instanceof Array) {
              //判断是否是数组
              file.map((v, i) => {
                v.status = "success";
                v.message = "";
                v.url = res.data[i];
                v.id = null;
              });
            } else {
              file.status = "success";
              file.message = "";
              file.url = res.data.imageUrl;
              if (this.bizBelongTo == 1) {
                this.signBoardImageList.push({
                  imagePath: res.data.imagePath,
                  fileSortNo: 1,
                  id: null,
                });
              } else {
                this.fullViewImageList.push({
                  imagePath: res.data.imagePath,
                  fileSortNo: this.fullViewImageList.length + 1,
                  id: null,
                });
              }
            }
          } else {
            return Promise.reject(res);
          }
        })
        .catch((err) => {
          Toast.fail(err.msg || "上传失败");
        });
    },

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值