美文网首页
微信小程序图片上传按比例压缩并转base64

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

作者: _Struggle_ | 来源:发表于2021-09-22 15:28 被阅读0次
      <canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;visibility:hidden;position:absolute;top:-10000rpx;left:-10000rpx;"></canvas>
     <van-uploader bind:after-read="onRead" wx:if="{{goodsItem.imgFile}}">
          <image src="{{goodsItem.imgFile}}" class='camera'></image>
        </van-uploader>
    
    //使用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

          本文链接:https://www.haomeiwen.com/subject/dgfggltx.html