手機端上傳照片壓縮功能canvas

手機上傳照片拍攝的照片像素很高需要壓縮後上傳,移動端前端壓縮照片的方法一般是用canvas,然後轉換成base64或者blob,發送後臺。

 <div class="img-btn1">
      <img class="img" src="@images/camore.png" alt v-if="imgShow1" />
      <img class="imgs" src alt id="newImage1" v-else />
      <input class="fileInpBtn" type="file" @change="showPicture1($event)" accept="image/*" multiple/>
  </div>

壓縮方法

  showPicture1(e) {
      if (e.target.files[0]) {
        this.imgShow1 = false;
        this.$vux.loading.show({
          text: "驗證中..."
        });
        // 獲取上傳文件的路徑,並賦給img標籤
        this.$nextTick(() => {
          document.getElementById("newImage1").src = window.URL.createObjectURL(
            e.target.files[0]
          );
        });
        // let formData = new FormData();
        // formData.append("file", e.target.files[0]); // 傳文件
        // formData.append("cardSide", "FRONT");
        // formData.append('openid', getSStore('openid'));
        var file = e.target.files[0];
        let size2 = Math.floor(file.size / 1024);
        let that = this;
        if (size2 > 1024) {
          // 大於2M,進行壓縮上傳
          this.photoCompress(file, function(filebase) {
            var params = {
              file: filebase,
              cardSide: "FRONT"
            };
            that.uploadImg(params);
          });
        } else {
          var reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            var imgcode = reader.result;
            // 讀取到的圖片base64 數據編碼 將此編碼字符串傳給後臺即可
            var params = {
              file: imgcode.replace(new RegExp("\\+", "gm"), "%2B"),
              cardSide: "FRONT"
            };
            this.uploadImg(params);
          };
        }
      }
    },
photoCompress: function(file, callback) {
      var that = this;
      var ready = new FileReader();
      /*開始讀取指定的Blob對象或File對象中的內容. 當讀取操作完成時,readyState屬性的值會成爲DONE,如果設置了onloadend事件處理程序,則調用之.同時,result屬性中將包含一個data: URL格式的字符串以表示所讀取文件的內容. */
      ready.readAsDataURL(file);
      ready.onload = function() {
        var re = this.result;
        var img = new Image();
        img.src = re;
        img.onload = function() {
          var that = this;
          // 默認按比例壓縮
          var w = 400;
          var h = (w * img.height) / img.width;
          var quality = 0.7; // 默認圖片質量爲0.7
          // 生成canvas
          var canvas = document.createElement("canvas");
          var ctx = canvas.getContext("2d");
          // 創建屬性節點
          var anw = document.createAttribute("width");
          anw.nodeValue = w;
          var anh = document.createAttribute("height");
          anh.nodeValue = h;
          canvas.setAttributeNode(anw);
          canvas.setAttributeNode(anh);
          ctx.drawImage(that, 0, 0, w, h);
          //也可以把壓縮後的圖片轉blob格式用於上傳
                // canvas.toBlob((blob)=>{
                //     console.log(blob)
                //     //把blob作爲參數傳給後端
                // }, 'image/jpeg', 0.92)
          // quality值越小,所繪製出的圖像越模糊
          var base64 = canvas.toDataURL("image/jpg", quality);
          // 正則替換哈 imgData 爲base64字符串
			base64.replace(/^data:image\/\w+;base64,/, "");
         // base64中,加號(+)是base64編碼的一部分,如果將+號轉變爲空格,就會導致解密失敗,所以要轉換成%2b。
          var filebase = base64.replace(new RegExp("\\+", "gm"), "%2B");
          callback(filebase);// 回調函數返回的值
        };
      };
    },
    uploadImg(params) {
      this.$http
        .uploadPost("/fileManager/fileUploadOcr", params)
        .then(res => {
          this.$vux.loading.hide();
          if (res.code === 0) {
            if (this.$route.query.action === "personalCenter") {
              this.$http.post("/customer/info", {}).then(response => {
                let identityNo = response.body.info.identityNo;
                if (identityNo !== res.body.IdNum) {
                  this.$vux.alert.show("身份證信息不匹配,請重新上傳!");
                  this.clearData();
                  this.imgShow1 = true;
                  document.getElementById("newImage1").src = "";
                } else {
                  this.identifyInfo.name = res.body.Name;
                  this.identifyInfo.Sex = res.body.Sex;
                  this.identifyInfo.Birth = res.body.Birth;
                  this.identifyInfo.IdNum = res.body.IdNum;
                }
              });
            } else {
              this.identifyInfo.name = res.body.Name;
              this.identifyInfo.Sex = res.body.Sex;
              this.identifyInfo.Birth = res.body.Birth;
              this.identifyInfo.IdNum = res.body.IdNum;
            }
          } else {
            this.clearData();
            this.imgShow1 = true;
            document.getElementById("newImage1").src = "";
          }
        })
        .catch(res => {
          this.clearData();
          this.imgShow1 = true;
          document.getElementById("newImage1").src = "";
        });
    },

在這裏插入圖片描述
參考網址:https://blog.csdn.net/huangpb123/article/details/80560980

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章