微信小程序:利用canvas缩小图片

功能分两部分:展示、提交
一期的时候,用户预览图片,直接提交到后台。但是发现如果图片太大,还要进行二次处理,还会降低接口相应速度等原因。所以要对图片进行压缩。

压缩原理:选择图片后,利用canvas的drawImage方法重新定义图片大小,再利用canvasToTempFilePath方法下载到缩小后图片。

// 利用绝对定位 隐藏canvas
<canvas canvas-id="photo_canvas" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position: absolute;left:-300px;top:-300px;"></canvas>
wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: function (photo) {
        wx.getImageInfo({
          src: photo.tempFilePaths[0],
          success: function(res){
            var ctx = wx.createCanvasContext('photo_canvas');
            var ratio = 2;
            var canvasWidth = res.width
            var canvasHeight = res.height;
            // 保证宽高均在200以内
            while (canvasWidth > 200 || canvasHeight > 200){
              //比例取整
              canvasWidth = Math.trunc(res.width / ratio)
              canvasHeight = Math.trunc(res.height / ratio)
              ratio++;
            }
            _this.setData({
              canvasWidth: canvasWidth,
              canvasHeight: canvasHeight
            })//设置canvas尺寸
            ctx.drawImage(photo.tempFilePaths[0], 0, 0, canvasWidth, canvasHeight)
            ctx.draw()
            //下载canvas图片
            setTimeout(function(){
              wx.canvasToTempFilePath({
                canvasId: 'photo_canvas',
                success: function (res) {
                  console.log(res.tempFilePath)
                },
                fail: function (error) {
                  console.log(error)
                }
              })
            },100)
          },
          fail: function(error){
            console.log(error)
          }
        })

      },
      error: function (res) {
        console.log(res);
      }
    })

猜你喜欢

转载自blog.csdn.net/akony/article/details/78815544