微信小程序图片上传按比例压缩并转base64

  
 
      
    
//使用vant组件或者使用wx.chooseImage都可以
  onRead(res1) {
    var that = this
    var imgPath = res1.detail.file.url
    var imgFile = 'goodsItem.imgFile'
    that.setData({
      [imgFile]:imgPath,
    })
    wx.getImageInfo({
      src:imgPath,
      success:function(res){
        var ratio = 2;
            var canvasWidth = res.width //图片原始长宽
            var canvasHeight = res.height
            while (canvasWidth > 400 || canvasHeight > 400){// 保证宽高在400以内
                canvasWidth = Math.trunc(res.width / ratio)
                canvasHeight = Math.trunc(res.height / ratio)
                ratio++;
            }
            that.setData({
                cWidth: canvasWidth,
                cHeight: canvasHeight
            })
             //----------绘制图形并取出图片路径--------------
             var ctx = wx.createCanvasContext('canvas')
             ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
             ctx.draw(false, setTimeout(function(){
                  wx.canvasToTempFilePath({
                      canvasId: 'canvas',
                      destWidth: canvasWidth,
                      destHeight: canvasHeight,
                      success: function (res) {
                          var filePath = res.tempFilePath
                          wx.getFileSystemManager().readFile({
                            filePath,
                              encoding: 'base64',
                              success:(res) =>{
                                // console.log('data:image/png;base64,' + res.data)
                                that.setData({
                                  file:'data:image/png;base64,' + res.data
                                })
                              }
                            })
                      },
                      fail: function (res) {
                          console.log(res.errMsg)
                     }
                 })
             },100)) 
      }
    }) 
  },

你可能感兴趣的:(微信小程序图片上传按比例压缩并转base64)