微信小程序上传图片使用canvas压缩

接上编文章使用官方compressImage进行压缩,效果很不错,但是有一个问题,就是官方api对png图片不压缩,这就很难了,后面查找资料,通过canvas相关api也可以对图片进行压缩,那么就开始吧

在这里插入图片描述

同样是布局

重点:这里必须把canvas挪出屏幕外,而且宽高必须限制,不然显示不出来

<button bindtap="changeImage">canvasNew压缩选择图片</button>
<!-- 将canvas挪出屏幕外 -->
<view style="position: fixed;top: -9999px;left: -9999px;">
    <canvas id="myCanvas" type="2d" style='border: 1px solid;width:{{cWidth}}rpx;height:{{cHeight}}rpx;' />
  </view>

选择图片

   changeImage: function (e) {
      var that = this;
      wx.chooseImage({
        sizeType:['original', 'compressed'],  //可选择原图或压缩后的图片
        sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
        success: result => {
          wx.getImageInfo({
            src: result.tempFilePaths[0],
            success: function (res) {
              console.log(res.width, res.height)
            //   that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality);
            const windowWidth= wx.getSystemInfoSync().windowWidth;
            let imgRatio = res.height/res.width;
              that.setData({
                cWidth: res.width,
                cHeight: windowWidth * imgRatio,
              }, () => {
                // setData引起的页面渲染完成之后的回调函数
                // setData渲染是异步的 canvasToTempFilePath的时候canvas的大小可能还没有被重新设置
                that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality);
              })
            }
          })
  
        }
      })
  
    },

canvasToTempFilePath绘制图片并压缩

    getCanvasImg(tempFilePaths, canvasWidth, canvasHeight, quality) {
      let query = wx.createSelectorQuery().in(this);
      query.select('#myCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');
        const image = canvas.createImage();
        image.src = tempFilePaths[0];
        //新接口需显示设置画布宽高;
        canvas.width = canvasWidth
        canvas.height = canvasHeight
        image.onload = () => {
        
          
          // 清除Canvas内容
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          
          // 在Canvas中绘制图片
          ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
          
          // 压缩图片
          wx.canvasToTempFilePath({
            canvas,
            fileType: 'jpg', // 可以根据需求修改为其他格式
            quality: 0.1, // 压缩质量,范围 0-1
            destWidth: canvasWidth,
            destHeight: canvasHeight,
            success: (res) => {
                this.setData({
                    imagePath: res.tempFilePath,
                    pic: [res.tempFilePath]
                });
                console.log('1',res.tempFilePath)
              // 压缩后的临时文件路径
               // 获取压缩后图片的信息,包括大小等
               wx.getFileSystemManager().getFileInfo({
                filePath: res.tempFilePath,
                success: fileInfo => {
                    this.setData({
                        compressSize: fileInfo.size / 1024 / 1024,
                        cWidth: canvas.width,
                        // cHeight:canvas.height 
                    })
                    console.log('压缩后图片大小:', fileInfo.size / 1024 / 1024); // 压缩后图片的大小,单位为字节
                    console.log('压缩成功',canvas.width, canvas.height)
                },
                fail: err => {
                    console.error('获取压缩后图片信息失败:', err);
                }
              });
            },
            fail: (err) => {
              // 压缩失败处理
              console.error('Canvas压缩失败:', err);
              wx.showModal({
                title: '提示',
                content: JSON.stringify(e),
              })
            }
          });
        };
      })
    },

效果如下:原图5兆多,压缩成356k,效果显著且清晰
在这里插入图片描述

如果大佬们有更好的办法可以沟通下,找不到第三方可用的

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值