微信小程序压缩图片

由于wx.compressImage(Object object) iOS 仅支持压缩 JPG 格式图片。所以我们需要做一下特殊的处理:

1.获取文件,判断文件是否大于设定的大小

2.如果大于则使用canvas进行绘制,并生成新的图片路径

3.上传图片

javascript 复制代码
async chooseImage() {
    let res = await wx.chooseMedia({
      count: 1,
      sizeType: ["compressed"],
      mediaType: ['image']
    })
    if (res.tempFiles[0].size > 500 * 1024) { //大于500k
        //压缩图片
      compressImage(res.tempFiles[0], '#canvasId').then(result => {
        this.uploadFile(result.tempFilePath)
      })
    } else {
      this.uploadFile(res.tempFiles[0].tempFilePath)
    }
  },
javascript 复制代码
const compressImage = function (file, node) {
  return new Promise((resolve, reject) => {
    //获取图片的信息
    wx.getImageInfo({
      src: file.tempFilePath,
      success: async function (imageInfo) {
        //获取canvas
        const query = wx.createSelectorQuery()
        let canvasDom = query.select(node) //画布id
        canvasDom.fields({
            node: true,
            size: true
          })
          .exec((res) => {
            const canvas = res[0].node
            canvas.width = 900 
            canvas.height = 900
            const ctx = canvas.getContext('2d')
            let img = canvas.createImage();
            img.src = imageInfo.path; //要压缩的图片路径
            img.onload = () => {
              // 将图片绘制到canvas
              ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
              // 生成图片
              wx.canvasToTempFilePath({
                canvas,
                destWidth: 900, //压缩后宽
                destHeight: 900, //压缩后高
                fileType: 'jpg',
                quality: 0.8, //质量,可自定义
                success: (imgResult) => {
                  let fs = wx.getFileSystemManager()
                  fs.getFileInfo({
                    filePath: imgResult.tempFilePath,
                    success: (res) => {
                        //压缩后的图片如果还是大于500k,那么继续压缩直到小于500为止
                      if (res.size > 500 * 1024) {
                        compressImage(imgResult)
                      } else {
                        resolve(imgResult)
                      }
                    }
                  })
                },
                fail: (err) => {
                  console.error(err);
                  reject(err)
                }
              })
            }
          })
      },
      fail: function (err) {
        console.error('获取图片信息失败:', err);
      }
    });
  })
}
javascript 复制代码
uploadFile(avatarUrl) {
    if (avatarUrl) {
      wx.uploadFile({
        filePath: avatarUrl,
        name: 'file',
        url: "http://139.224.49.138:888/mini/myPage/uploadAvatar",
        formData: {
          openid: getApp().globalData.openid
        },
        success: (res) => {
          let {
            userInfo
          } = app.store.getState();
          userInfo.headPic = JSON.parse(res.data).url
          app.store.setState({
            userInfo: userInfo
          });
        },
        fail: err => {
          console.log(err);
        }
      })
    }
  },
html 复制代码
<canvas hidden="{
  
  {true}}" type="2d" id="canvasId"/>
相关推荐
沙尘暴炒饭6 小时前
用uniapp在微信小程序实现画板(电子签名)功能,使用canvas实现功能
微信小程序·小程序·uni-app
PyAIGCMaster10 小时前
Taro 编译不平不同平台小程序
小程序
fakaifa1 天前
【开源版】likeshop上门家政系统PHP版全开源+uniapp前端
小程序·uni-app·php·家政小程序源码·家政服务小程序·源码下载·上门家政
说私域1 天前
基于定制开发开源AI智能名片S2B2C商城小程序的公私域流量融合运营策略研究
人工智能·小程序·开源·零售
阿諪諪1 天前
uniapp小程序中实现无缝衔接滚动效果
小程序·uni-app
爱分享的程序员1 天前
小程序多线程实战
微信小程序
AALoveTouch1 天前
霸王茶姬微信小程序自动化签到系统完整实现&解析
微信小程序·自动化·notepad++
我是小伍同学2 天前
基于卷积神经网络和Pyqt5的猫狗识别小程序
人工智能·python·神经网络·qt·小程序·cnn
GalenWu2 天前
对象转换为 JSON 字符串(或反向解析)
前端·javascript·微信小程序·json
爱分享的程序员2 天前
小程序消息订阅的整个实现流程
小程序