微信小程序利用canva进行大图片压缩

找了很多方法没找到合适的图片压缩第三方库,有没有推荐的微信小程序压缩图片的第三方库呀(有的话,互帮互助,感谢)

我自己写了个简易的压缩方法,其实就是等比例的缩小图片,并把png转为jpg,毕竟png的颜色太多。

wxml:

<canvas canvas-id="canvas" class="my-canvas" style="width:{{cWidth}}px;height:{{cHeight}}px">
</canvas>

js:

 canvasCompress(obj, n) {
    let {
      tempFiles
    } = this.data
    let _this = this
    return new Promise((resolve, reject) => {
      let canvasWidth = obj.params.width
      let canvasHeight = obj.params.height
      console.log(canvasWidth);
      let quality = 0.8
      if (canvasWidth > 750) {
        canvasWidth = 750
        canvasHeight = Math.trunc(obj.params.height * 750 / obj.params.width)
        quality = 0.5
      } else if (canvasWidth > 400 && canvasWidth < 749) {
        canvasWidth = 400
        canvasHeight = Math.trunc(obj.params.height * 400 / obj.params.width)
        quality = 0.6
      }
      this.setData({
        cWidth: canvasWidth,
        cHeight: canvasHeight
      })
      let ctx = wx.createCanvasContext('canvas')
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      ctx.drawImage(tempFiles[n].tempFilePath, 0, 0, canvasWidth, canvasHeight)
      ctx.draw(false, _this.timer = setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'canvas',
          destWidth: canvasWidth, // 输出图片的宽度
          destHeight: canvasHeight, // 输出图片的高度
          fileType: 'jpg', // 图片输出格式
          quality: 0.5, // 图片质量 0-1
          success: function (res) {
            clearTimeout(_this.timer)
            resolve(res.tempFilePath);
          },
          fail: function (res) {
            clearTimeout(_this.timer)
            reject(err.errMsg)
          }
        })
      }, 600)) //留一定的时间绘制canvas
    })
  },

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值