微信小程序压缩图片到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)
        }
      })
    },
相关推荐
我命由我1234510 小时前
微信小程序 - 页面跳转并传递参数(使用路由参数、使用全局变量、使用本地存储、使用路由参数结合本地存储)
开发语言·前端·javascript·微信小程序·小程序·前端框架·js
00后程序员张10 小时前
数据流抓包实战指南,TCPUDP 流量分析、HTTPS 解密与多工具协同方案
网络协议·http·ios·小程序·https·uni-app·iphone
2501_9159214310 小时前
iOS 性能分析工具全景解析,构建从底层诊断到真机监控的多层级性能分析体系
android·ios·小程序·https·uni-app·iphone·webview
2501_9159090611 小时前
如何防止 IPA 被反编译,从攻防视角构建一套真正有效的 iOS 成品保护体系
android·macos·ios·小程序·uni-app·cocoa·iphone
毕设源码-邱学长11 小时前
【开题答辩全过程】以 基于微信小程序的社区老年人活动中心信息管理系统的设计与实现 为例,包含答辩的问题和答案
微信小程序·小程序
2501_9160074711 小时前
专业的 IPA 处理工具 构建可维护、可回滚的 iOS 成品加工与加固流水线
android·ios·小程序·https·uni-app·iphone·webview
游戏开发爱好者811 小时前
Charles抓包工具怎么用 Charles抓包教程、网络调试技巧与HTTPS配置全流程
网络·ios·小程序·https·uni-app·php·webview
说私域11 小时前
MarTech在客户运营中的作用:以开源AI大模型AI智能名片S2B2C商城小程序为例
人工智能·小程序·开源
烂不烂问厨房11 小时前
支付宝小程序camera录制视频超过30秒无法触发cameraContext.stopRecord回调,也没报错
android·小程序