微信小程序压缩图片到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)
        }
      })
    },
相关推荐
走,带你去玩1 小时前
uniapp 微信小程序水印
微信小程序·小程序·uni-app
是一碗螺丝粉1 小时前
🔥 微信H5视频自动播放终极秘籍:WeixinJSBridge竟是官方“通行证”?
微信小程序
一笑code2 小时前
vue/微信小程序/h5 实现react的boundary
微信小程序·vue·react
菌菇汤4 小时前
uni-app实现单选,多选也能搜索,勾选,选择,回显
前端·javascript·vue.js·微信小程序·uni-app·app
CC同学呀11 小时前
从0到100:单位订餐统计小程序开发日记2025
小程序
666HZ66616 小时前
微信小程序中scss、ts、wxml
微信小程序·小程序·scss
二十十十十十17 小时前
微信点餐小程序—美食物
微信·小程序
向明天乄17 小时前
在小程序中实现实时聊天:WebSocket最佳实践
websocket·网络协议·小程序
h1853859224417 小时前
租车小程序电动车租赁小程序php方案
小程序
海的诗篇_17 小时前
前端开发面试题总结-原生小程序部分
前端·javascript·面试·小程序·vue·html