微信小程序压缩图片到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 小时前
uniapp与蓝牙设备连接详细步骤
前端·微信小程序
万岳科技系统开发13 小时前
私域直播系统开发从0到1:企业直播平台搭建全过程
前端·小程序·架构
2501_9160074714 小时前
iOS应用性能优化全面指南:从内存管理到工具使用
android·ios·性能优化·小程序·uni-app·iphone·webview
i220818 Faiz Ul15 小时前
理财系统|基于java+vue的家庭理财系统小程序(源码+数据库+文档)
java·vue.js·spring boot·小程序·论文·毕设·理财系统
河北清兮网络科技15 小时前
企业软件开发全流程:从需求到上线,如何高效落地?
小程序·app·短剧·短剧app·广告联盟
维双云19 小时前
想做企业公司的教育知识付费小程序多少钱?
小程序
huang_jimei19 小时前
【无标题】
微信小程序
柚鸥ASO优化19 小时前
微信正在变成“搜索引擎”:小程序SEO机会全面爆发
搜索引擎·微信·小程序·小程序优化
Brave & Real1 天前
小程序 const 在js中以及与同类的var和let之间的差异
javascript·微信小程序·小程序
Joolun商城源码_Java1 天前
JooLun Pro旗舰版SaaS多租户商城:商城小程序与店铺小程序的功能区别详解
小程序