微信小程式開發-canves 圖片壓縮 獲取base64

giserinchina發表於2020-10-22
makeCanvas: function(imgPath) {
      console.log("start draw");
      var ctx = wx.createCanvasContext('canvas')
      // 設定背景
      ctx.setFillStyle('#ffffff')
      ctx.fillRect(0, 0, this.data.canvasWidth, this.data.canvasWidth)



      // 描繪圖片
      /**
       * @function drawImage Canvas描繪圖片
       * @param {String} imgPath 圖片路徑
       * @param {Number} imgWidth 圖片寬度
       * @param {Number} imgHeight 圖片高度
       * @author mossbaoo
       */
       let cWidth = this.data.canvasWidth*0.5;
        let cHeight = this.data.canvasWidth*0.5;
        let imgWidth = this.data.imgInfo.width;
        let imgHeight = this.data.imgInfo.height
        console.log(cWidth+"_"+cHeight+"_"+imgWidth+"_"+imgHeight);
        let dWidth = cWidth/imgWidth;  // canvas與圖片的寬度比例
        let dHeight = cHeight/imgHeight;  // canvas與圖片的高度比例
        if (imgWidth > cWidth && imgHeight > cHeight || imgWidth < cWidth && imgHeight < cHeight) {
          if (dWidth > dHeight) {
            ctx.drawImage(imgPath, 0, (imgHeight - cHeight/dWidth)/2, imgWidth, cHeight/dWidth, 0, 0, cWidth, cHeight)
          } else {
            ctx.drawImage(imgPath, (imgWidth - cWidth/dHeight)/2, 0, cWidth/dHeight, imgHeight, 0, 0, cWidth, cHeight)
          }
        } else {
          if (imgWidth < cWidth) {
            ctx.drawImage(imgPath, 0, (imgHeight - cHeight/dWidth)/2, imgWidth, cHeight/dWidth, 0, 0, cWidth, cHeight)
          } else {
            ctx.drawImage(imgPath, (imgWidth - cWidth/dHeight)/2, 0, cWidth/dHeight, imgHeight, 0, 0, cWidth, cHeight)
          }
        }


      ctx.draw();
      console.log("end draw");
      debugger;
      var that = this;
      wx.canvasToTempFilePath({
            canvasId: 'canvas',
            success: function success(res) {
              that.setData({
                canvasImgUrl: res.tempFilePath
              });
              that.canvasShow=false;
              console.log(res.tempFilePath);
              // 人臉驗證
              let base64 = wx.getFileSystemManager().readFileSync(res.tempFilePath, 'base64');

              console.log("base64two:"+base64.length);
              if (!that.isLoading) {
                  that.setData({
                      isLoading: !0
                  });
                  //先活體face/faceVerify
                  that.vertifyImg(base64);
              }

            },
            complete: function complete(e) {
            }
          });
    }

 

相關文章