微信小程序压缩图片到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 小时前
微信小程序全局配置
微信小程序·小程序
Enti7c2 小时前
微信小程序核心知识点速览
微信小程序·小程序
2501_9159184114 小时前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview
说私域16 小时前
从品牌附庸到自我表达:定制开发开源AI智能名片S2B2C商城小程序赋能下的营销变革
人工智能·小程序
難釋懷16 小时前
第一个小程序
小程序
春哥的研究所16 小时前
可视化DIY小程序工具!开源拖拽式源码系统,自由搭建,完整的源代码包分享
小程序·开源·开源拖拽式源码系统·开源拖拽式源码·开源拖拽式系统
weixin_lynhgworld16 小时前
盲盒一番赏小程序技术实现方案:高并发与防作弊的平衡之道
小程序
今日热点17 小时前
小程序主体变更全攻略:流程、资料与异常处理方案
经验分享·微信·小程序·企业微信·微信公众平台·微信开放平台
鸭鸭梨吖21 小时前
微信小程序---下拉框
微信小程序·小程序
CRMEB定制开发1 天前
CRMEB Pro版前端环境配置指南
前端·微信小程序·uni-app·商城源码·微信商城·crmeb