微信小程序压缩图片到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)
        }
      })
    },
相关推荐
说私域2 小时前
从大众传媒到数字生态:开源AI智能名片链动2+1模式S2B2C商城小程序驱动的营销革命
人工智能·小程序·开源·零售
换日线°2 小时前
微信小程序连续多个特殊字符自动换行解决方法
微信小程序
海拥3 小时前
《用Cursor和AI绘画24小时开发壁纸小程序》详细开发实录
微信小程序·cursor
10年前端老司机6 小时前
微信小程序behaviors
前端·javascript·微信小程序
山河故人1636 小时前
基于 SSE 和分块传输的 Uniapp 微信小程序 实现 流式传输 对话
微信小程序·小程序·uni-app
10年前端老司机7 小时前
微信小程序自定义组件
前端·javascript·微信小程序
Maitians7 小时前
微信小程序 template 模版详解
微信小程序
说私域11 小时前
开源AI智能名片链动2+1模式S2B2C商城小程序源码赋能下的社交电商创业者技能跃迁与价值重构
人工智能·小程序·重构·开源·零售
中小企业实战军师刘孙亮21 小时前
实体店的小程序转型之路:拥抱新零售的密码-中小企实战运营和营销工作室博客
职场和发展·小程序·创业创新·学习方法·业界资讯·零售·内容运营
说私域21 小时前
基于开源技术体系的品牌赛道力重构:AI智能名片与S2B2C商城小程序源码驱动的品类创新机制研究
人工智能·小程序·重构·开源·零售