微信小程序压缩图片

由于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"/>
相关推荐
haojiehero1231 小时前
壹佰商城源码搭建-支持打包小程序/公众号/app/h5网页-支持分销-各种营销功能强大
小程序
嗷呜小熊熊2 小时前
唤起小程序呕血总结
微信小程序
H0483 小时前
记录uni-app使用plus注意事项【AI生成】
前端·微信小程序
z.week8 小时前
小程序网络大文件缓存方案
缓存·小程序
huiguoyuan9 小时前
微信小程序审核失败,你的小程序涉及提供播放、观看等服务,请补充选择:文娱-其他视频类目 解决
小程序
雯0609~9 小时前
微信小程序:实现多功能表格效果,例如滚动效果、宽度自定义、多选、行内编辑等功能
微信小程序·小程序·notepad++
余道各努力,千里自同风9 小时前
微信小程序wx.request接口报错(errno: 600001, errMsg: “request:fail -2:net::ERR_FAILED“)
微信小程序·小程序
java_python源码9 小时前
【2025】基于springboot+vue+uniapp的厨师预约上门做菜小程序(源码、万字文档、图文修改、调试答疑)
vue.js·小程序·uni-app
朱剑君10 小时前
用Python写一个天气预报小程序
python·小程序
橘猫云计算机设计12 小时前
基于Java 童装在线销售系统(源码+lw+部署文档+讲解),源码可白嫖!
java·服务器·数据库·spring boot·后端·小程序