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

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

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

wxml:


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
    })
  },

你可能感兴趣的:(javascript,前端,开发语言,微信小程序,小程序)