微信小程序压缩图片到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)
        }
      })
    },
相关推荐
多看书少吃饭11 小时前
小程序支持HTTP POST 流式接口吗?
网络协议·http·小程序
询问QQ:48773927814 小时前
CDB文件第0x2C位置存放温度阈值
小程序
vx_vxbs6615 小时前
【SSM高校普法系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
android·java·python·mysql·小程序·php·idea
吹水一流16 小时前
微信小程序页面栈:从一个 Bug 讲到彻底搞懂
前端·微信小程序
duansamve19 小时前
支付宝小程序开发工具中如何模拟给页面传参?
小程序·支付宝小程序
低代码布道师19 小时前
医疗预约小程序原型设计
低代码·小程序
星光一影19 小时前
同城派送系统源码,支持小程序,h5,app
mysql·小程序·php·uniapp
说私域20 小时前
基于链动2+1模式AI智能名片S2B2C商城小程序的微商运营内容研究
大数据·人工智能·小程序
Jing_Rainbow20 小时前
【 Weapp-3 /Lesson20(2025-11-04)】路虎卫士小程序开发详解:从架构到细节的深度解析🚙📱
微信·微信小程序·程序员