读心悦

  • 读心随笔
  • 读心里话
  • 计算机
  1. 首页
  2. 小程序
  3. 正文

小程序图片压缩

2020年09月16日 155点热度 0人点赞 0条评论

在开发小程序时,需要上传图片到服务器中,并且限制图片大小不能超过100kb,所以在选择图片或者拍照之后进行图片压缩再上传到服务器中。那么压缩图片有以下几种方式:

使用wx.chooseImage

wx.chooseImage选择图片或者调用相机拍照的时候,设置为缩略图,自动压缩。
但是这种方式不能设置具体压缩多少,就像要求图片不能大于100kb,这种时候wx.chooseImage压缩下来不一定是小于100kb。

通过canvas压缩图片

思路:
1、读取图片的大小【 wx.getFileInfo()读取文件大小的相关信息】;
2、若是图片不符合我们的要求,通过canvas对图片进行编辑压缩。【wx.getImageInfo()获取图片的尺寸相关信息】

canvas压缩图片的步骤:

1、将我们拍照的图片通过CanvasContext.drawImage绘制到画布上(canvas)
2、把之前绘图的上下文描述通过CanvasContext.draw画到canvas上。
3、在draw()的回调使用wx.canvasToTempFilePath导出图片,再次读取该图片的大小,判断是否符合我们的要求。

wxml:

<camera device-position="front" flash="off" binderror="error" class="photo" wx:if="{{hide}}"></camera>
  <view class="btn-area" wx:if="{{hide}}">
    <button type="primary" bindtap="takePhoto">拍照</button>
  </view>
  <view class="preview">
    <!-- <view class="preview-tips">预览</view> -->
    <image wx:if="{{src}}" mode="widthFix" src="{{src}}"></image>
  </view>

  </view>

<canvas canvas-id='pressCanvas' class='press-canvas' style='width: {{ canvasWidth }}px; height: {{ canvasHeight }}px;position:absolute;left:{{-canvasWidth}}px;bottom:{{-canvasHeight}}px' wx:if="{{canvas}}"></canvas> 

压缩图片的方法:

  //图片压缩
  compressImage(imgpath) {
    const that = this;
    wx.showLoading({
      title: '压缩中...',
      mask: true,
    })
    wx.getFileInfo({
      filePath: imgpath,
      success: (result) => {
        console.log(result)
        console.log("图片压缩前=" + result.size / 1024 + "kByte");
        if (result.size / 1024 > 90) {
          wx.getImageInfo({
            src: imgpath,
            success(rr) {
              var ctx = wx.createCanvasContext('pressCanvas');
              var ratio = 1;
              var canvasWidth = rr.width
              var canvasHeight = rr.height;
              //设置canvas尺寸
              that.setData({
                canvasWidth: canvasWidth,
                canvasHeight: canvasHeight
              });
              ctx.drawImage(imgpath, 0, 0,300, 300); //将图片填充在canvas上
              ctx.draw(false, setTimeout(function() {
                wx.canvasToTempFilePath({
                  canvasId: 'pressCanvas',
                  
                  destWidth:300,  //设置导出目标图片宽度
                  destHeight:300, //设置导出目标图片的高度
                  fileType: 'jpg',
                  quality: 0.6,
                  success: function success(path) {
                    wx.getFileInfo({
                      filePath: path.tempFilePath,
                      success(data) {
                        console.log("压缩后图片大小为==" + data.size / 1024 + "kb");
                        if (data.size / 1024 > 80) {
                          console.log("图片太大了")
                          that.compressImage(path.tempFilePath)
                        } else {
                          wx.hideLoading();
                          that.setData({
                            hide: false,
                            src: path.tempFilePath,
                            canvas: true
                          })
                          console.log("图片符合要求")
                          
                        }
                      }
                    })
                  },
                  fail: function fail(e) {}
                });
              }, 1000));
            }
          })
        } else {
          wx.hideLoading();
          that.setData({
            hide: false,
            src: imgpath,
            canvas: true
          })
          
          wx.showToast({
            title: '图片小于100KB',
          })
        }
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  }

拍照按钮的点击事件:

  // 拍照
  takePhoto() {
    const that = this;
    // 从相册选择图片或者使用相机拍照后设置图片为缩略图
    // wx.chooseImage({
    //   count: 1,
    //   sizeType: ['original', 'compressed'],
    //   sourceType: ['album', 'camera'],
    //   success(res) {
    //     that.transformBase(res.tempFilePaths[0])
    //     wx.getFileInfo({
    //       filePath: res.tempFilePaths[0],
    //       success(data) {
    //         console.log("图片大小=" + data.size / 1024 + "kb")
    //       }
    //     })
    //     that.setData({
    //       hide: false,
    //       src: res.tempFilePaths
    //     })
    //   }
    // })
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        console.log(res)
        that.compressImage(res.tempImagePath);
        // wx.getFileInfo({
        //   filePath: res.tempImagePath,
        //   // digestAlgorithm: '',
        //   success: function(option) {
        //     console.log("压缩前图片大小为:" + option.size / 1024 + "kb");

        //     if (option.size / 1024 > 90) {
        //       // 压缩
        //       wx.compressImage({
        //         src: res.tempImagePath, // 图片路径
        //         quality: 80, // 压缩质量
        //         success: (e) => {
        //           console.log(e)
        //           that.setData({
        //             hide: false,
        //             src: e.tempFilePath,
        //             canvas: true
        //           })
        //           
        //           wx.getFileInfo({
        //             filePath: e.tempFilePath,
        //             // digestAlgorithm: '',
        //             success: function(option) {
        //               console.log("压缩后图片大小为:" + option.size / 1024 + "kb")
        //             },
        //             fail: function(error) {
        //               console.log(error)
        //             },
        //           })
        //         }
        //       })
        //     } else {
        //       console.log("图片符合要求")
        //       that.setData({
        //         hide: false,
        //         src: res.tempImagePath,
        //         canvas: true
        //       })
        //       that.transformBase(res.tempImagePath);
        //     }
        //   },
        //   fail: function(error) {
        //     console.log(error)
        //   },
        // })


      }
    })
  },

通过wx.compressImage来压缩图片

如以上代码this.ctx.takePhoto中的注释部分,就不需要使用canvas了,拍照好了之后直接读取图片的大小,判断是否符合要求,否则通过wx.compressImage进行压缩。

赞微海报分享
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 小程序
最后更新:2020年10月14日

读心悦

自己从事开发也有一段时间了,总有一些迷茫,对未来有一点恐惧,不知道以后会不会继续从事开发的岗位。无论未来做出怎样的选择,这个网站就记录一下从事开发这段时间的一些笔记、阅读笔记吧,好歹也给自己留个纪念吧,你说呢! 写点代码,读点书,读点心,读点自己!

打赏 点赞
< 上一篇
下一篇 >

文章评论

取消回复

读心悦

自己从事开发也有一段时间了,总有一些迷茫,对未来有一点恐惧,不知道以后会不会继续从事开发的岗位。无论未来做出怎样的选择,这个网站就记录一下从事开发这段时间的一些笔记、阅读笔记吧,好歹也给自己留个纪念吧,你说呢! 写点代码,读点书,读点心,读点自己!

标签聚合
闲谈 阅读 taro vue redux node hook mysql Echarts Nginx 悦读 git JavaScript canvas 小程序 flutter 随笔 CSS react
推荐文章
  1. 微信小程序中自定义导航和地图定位
  2. 微信小程序上传图片
  3. 微信小程序前端解密获取用户信息
  4. 小程序云开发·数据库
分类
  • flutter (11)
  • html/css (23)
  • Javascript (22)
  • Mysql (2)
  • node (2)
  • React (27)
  • vue (1)
  • 小程序 (41)
  • 悦读 (8)
  • 未分类 (2)
  • 读心里话 (9)

COPYRIGHT © 2020 读心悦

黔ICP备20005501号

黔公网安备52011502001078号