微信小程序压缩图片到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)
        }
      })
    },
相关推荐
花卷HJ2 小时前
微信小程序国际化完整方案
微信小程序·小程序·notepad++
2501_916008892 小时前
2026 iOS 证书管理,告别钥匙串依赖,构建可复制的签名环境
android·ios·小程序·https·uni-app·iphone·webview
nhc0882 小时前
贵阳纳海川科技・上门洗车行业解决方案
科技·微信小程序·软件开发·小程序开发
土土哥V_araolin3 小时前
十二星商城小公排系统开发
小程序·个人开发·零售
hashiqimiya3 小时前
微信小程序--动态切换登录注册标签页
微信小程序·小程序
hashiqimiya4 小时前
微信小程序--获取验证码设计倒计时灰白色
微信小程序·小程序
weixin_lynhgworld6 小时前
电商营销新风口,淘宝扭蛋机小程序引爆流量与转化
小程序
2501_933907217 小时前
宁波小程序公司提供专业的小程序开发服务
科技·微信小程序·小程序
杰建云1678 小时前
小程序搭建如何影响企业数字化转型
小程序·小程序制作
2501_915918418 小时前
iOS App 拿不到数据怎么办?数据解密导出到分析结构方法
android·macos·ios·小程序·uni-app·cocoa·iphone