其他分享
首页 > 其他分享> > vue+eleme upload 上传图片(含gif动图) canvas压缩转blob对象

vue+eleme upload 上传图片(含gif动图) canvas压缩转blob对象

作者:互联网

突然新增个需求,下、图片上传需要支持gif动图
以前的项目是通过canvas压缩的方式,但是通过这种方式,出现即使结果是.gif文件,但实际上,并不是动图
直接看下面代码

// 压缩图片
    compress(img) {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      // let initSize = img.src.length;
      const width = img.width;
      const height = img.height;
      canvas.width = width;
      canvas.height = height;
      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, width, height);
      // 进行压缩
      const ndata = canvas.toDataURL("image/jpeg", 0.8);
      return ndata;
    },
   // base64转成bolb对象
    dataURItoBlob(base64Data) {
      let byteString;
      if (base64Data.split(",")[0].indexOf("base64") >= 0) {
        byteString = atob(base64Data.split(",")[1]);
      } else {
        byteString = unescape(base64Data.split(",")[1]);
      }
      const mimeString = base64Data.split(",")[0].split(":")[1].split(";")[0];
      const ia = new Uint8Array(byteString.length);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], { type: mimeString });
    },
    async upload(data) {
      // 自定义upload事件
      const img = new Image();
      img.src = this.file.url;
      img.onload = async () => {
        const _data = this.compress(img);
        let blob = this.dataURItoBlob(_data);
		//重点来了
        if(this.file.name.includes('gif')){
          await fetch(this.file.url)
          .then((response) => response.blob())
          .then((res) => {
            blob = res
          });
        }
        const formData = new FormData();
        formData.append("file", blob, this.file.name); // 有的后台需要传文件名,不然会报错
        // formData.append('imageDesc', this.imageDesc) // 图片说明
        formData.append("filePath", this.filePath);

        //this.imgUpload(formData);
      };
    },

标签:canvas,vue,const,img,height,width,动图,byteString
来源: https://blog.csdn.net/weixin_44730897/article/details/117933975