微信小程序压缩图片到200kb,递归设置压缩质量

一、背景

我们有个人脸识别门闸的功能,小程序上上传人脸照片,然后门闸识别人脸开门。图片大小要在在200kb,但是也不能压缩的太小,因为大小有可能识别不到或者要走很近才能识别。所以选择递归的方式实现图片的压缩。

二、代码实现

c 复制代码
  toTakePhoto(){
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed'],
        success: (res) => {
          console.log(res, 111)
          wx.showLoading({
            title: '图片上传中',
          })
          let tempFile = res.tempFiles && res.tempFiles[0] ? res.tempFiles[0] : ""
          let Filesize = tempFile.size / 1024 //文件大小默认为B换算为KB
          if (tempFile.tempFilePath) {
            this.setData({
              "form.visitor_img": ""
            })
            console.log(Filesize, "Filesize")
            if (Filesize && Filesize < 200) {
              this.toCheckPhoto(tempFile.tempFilePath)
            } else {
              this.compressImage(tempFile.tempFilePath)
            }
          }
        }
      })
    },
    compressImage(tempFilePath, quality = 100) {
      wx.compressImage({
        src: tempFilePath,
        compressedHeight: 432,
        compressedWidth: 352,
        quality,
        success: (re) => {
          console.log('compressImage-----', re);
          console.log(quality, "quality")
          if (this.isPhotoSizeOk(re.tempFilePath)) {
            this.toCheckPhoto(re.tempFilePath)
          } else {
            if (quality > 0) {
              this.compressImage(tempFilePathh, quality - 10)
            } else {
              //确定提交
              if (!this.isPhotoSizeOk(re.tempFilePath)) {
                wx.showToast({
                  title: "图片需小于200k",
                  icon: "none"
                })
              }
            }
          }
        },
        fail: (err) => {
          console.log('compressImage-----fail', err);
          this.isPhotoSizeOk(re.tempFilePath)
        }
      })
    },
相关推荐
黄华SJ520it3 小时前
139小程序商城模式开发
小程序·软件需求·系统开发
Greg_Zhong3 小时前
详细说下小程序中使用canvas的体验
小程序·canvas绘制·canvas绘制内容溢出·绘制内容模拟器不正常·绘制内容真机正常
小羊Yveesss6 小时前
2026 多门店小程序如何提升效率?连锁门店降本增效实操指南,数字化转型必看
大数据·小程序
2501_941982056 小时前
提高私域转化率:如何通过 API 自动发送小程序卡片?
小程序·机器人·自动化·企业微信·rpa
码视野10 小时前
完全开源-支持二开-可做毕业论文-家政服务预约小程序
小程序
码视野10 小时前
全开源-健身运动预约小程序 — 从需求到原型的全栈实践
小程序
游戏开发爱好者811 小时前
深入理解iOSTime Profiler:提升iOS应用性能的关键工具
android·ios·小程序·https·uni-app·iphone·webview
tianxiaxue111 小时前
微信小程序如何跟企微互通
微信小程序·小程序·企业微信
Greg_Zhong11 小时前
微信小程序中canvas绘制面积图,解决手机和模拟器都能渲染不溢出问题
微信小程序·小程序canvas绘制面积图
小小王app小程序开发12 小时前
潮玩抽赏盲盒小程序玩法分析:2026 潮玩风口,技术合规双驱动
小程序