微信小程序压缩图片

由于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"/>
相关推荐
weixin_lynhgworld4 小时前
从闲置到珍宝:旧物回收小程序系统重塑物品价值
小程序·旧物回收
2501_916007479 小时前
iOS App 上架实战 从内测到应用商店发布的全周期流程解析
android·ios·小程序·https·uni-app·iphone·webview
小小怪下士_---_14 小时前
uniapp开发微信小程序自定义导航栏
前端·vue.js·微信小程序·小程序·uni-app
摸着石头过河的石头16 小时前
小程序调试全攻略:微信/支付宝避坑指南,小白也能一次通关
前端·微信小程序
fakaifa1 天前
点大餐饮独立版系统源码v1.0.3+uniapp前端+搭建教程
小程序·uni-app·php·源码下载·点大餐饮·扫码点单
Dignity_呱1 天前
如何在不发版时,实现小程序的 AB 测试?
前端·面试·微信小程序
说私域2 天前
基于开源 AI 大模型 AI 智能名片 S2B2C 商城小程序视角下的企业组织能力建设与破圈升级
人工智能·小程序
fakaifa2 天前
【最新版】CRMEB Pro版v3.4系统源码全开源+PC端+uniapp前端+搭建教程
人工智能·小程序·uni-app·php·crmeb·源码下载·crmebpro
2501_915918412 天前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview
上海云盾第一敬业销售2 天前
小程序被爬虫攻击,使用waf能防护吗?
爬虫·小程序