小程序压缩图片

wx.compressImage(Object object)

https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.compressImage.html

示例代码

wx.compressImage({
  src: '', // 图片路径
  quality: 80 // 压缩质量
})

Object object

属性类型默认值必填说明
srcstring 图片路径,图片的路径,支持本地路径、代码包路径
qualitynumber80压缩质量,范围0~100,数值越小,质量越低,压缩率越高(仅对jpg有效)。
successfunction 接口调用成功的回调函数
failfunction 接口调用失败的回调函数
completefunction 接口调用结束的回调函数(调用成功、失败都会执行)

回调函数里返回的是tempFilePath,而且返回的类型是string,不是string数组,切记不要跟wx.chooseImage的返回值搞混淆了

const app = getApp()

Page({
  data: {

  },
  onLoad: function() {
    console.log('代码片段是一种迷你、可分享的小程序或小游戏项目,可用于分享小程序和小游戏的开发经验、展示组件和 API 的使用、复现开发问题和 Bug 等。可点击以下链接查看代码片段的详细文档:')
    console.log('https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/devtools.html')
  },
  doImage: function(path) {
    wx.compressImage({
      src: path, // 图片路径
      quality: 80, // 压缩质量
      success: res => {
        let tempFile = res.tempFilePath
        wx.getFileInfo({
          filePath: tempFile,
          success(res) {
            let picSize = res.size
            console.log("压缩:", picSize / 1000)
          }
        })
      },
      fail: error => {
        console.log("error", error)
      }
    })
  },
  chooseImage: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.getFileInfo({
          filePath: tempFilePaths[0],
          success(res) {
            let picSize = res.size
            console.log("未压缩:", picSize / 1000)
          }
        })
        that.doImage(tempFilePaths[0]);
      }
    })
  }
})

 

注意在开发者工具中是不能调试的,换句话说这个api虽然在开发者工具中不会报错,但是也并不会有什么作用,需要到真机上才能生效。这个在文档上是没有说的。需要自己指定fail回调才会发现有错误。 这是第一个坑。

第二个坑在于,success回调函数是有参数的。这在文档里也没有体现,光看文档我还以为压缩后文件的路径就是原路径,我是凭经验觉得这个回调函数应该是有一个参数的。这个回调函数的参数包含了压缩后文件的路径tempFilePath。 如果是刚接触小程序开发的话,很容易就被坑了。这是第二个坑。 

 

 

其他方式参考: 

wx.chooseImage({
     success(res) {
       console.log(res)
       const tempFilePaths = res.tempFilePaths;
 
       //获得原始图片大小
       wx.getImageInfo({
         src: res.tempFilePaths[0],
         success(res) {
           // console.log('获得原始图片大小',res.width)
           //console.log(res.height)
           var originWidth, originHeight;
           originHeight = res.height;
           originWidth = res.width;
           console.log(originWidth);
           //压缩比例
           // 最大尺寸限制
           var maxWidth = 1200,
             maxHeight = 600;
           // 目标尺寸
           var targetWidth = originWidth,
             targetHeight = originHeight;
           //等比例压缩,如果宽度大于高度,则宽度优先,否则高度优先
           if (originWidth > maxWidth || originHeight > maxHeight) {
             if (originWidth / originHeight > maxWidth / maxHeight) {
               // 要求宽度*(原生图片比例)=新图片尺寸
               targetWidth = maxWidth;
               targetHeight = Math.round(maxWidth * (originHeight / originWidth));
             } else {
               targetHeight = maxHeight;
               targetWidth = Math.round(maxHeight * (originWidth / originHeight));
             }
           }
           //尝试压缩文件,创建 canvas
           var ctx = wx.createCanvasContext('firstCanvas');
           ctx.clearRect(0, 0, targetWidth, targetHeight);
           ctx.drawImage(tempFilePaths[0], 0, 0, targetWidth, targetHeight);
           ctx.draw();
           //更新canvas大小
           that.setData({
             cw: targetWidth,
             ch: targetHeight
           });
           //保存图片
           setTimeout(function() {
             wx.canvasToTempFilePath({
               canvasId: 'firstCanvas',
               success: (res) => {
                 //写入图片数组
                 var uploadpic = "uploadPic[" + index + "]";
                 //
                 that.setData({
                   [uploadpic]: res.tempFilePath
                 });
                 uploadFile = res.tempFilePath;
                 //保存到相册
                 // wx.saveImageToPhotosAlbum({
                 //   filePath: res.tempFilePath,
                 //   success: (res) => {
                 //     console.log(res)
                 //   },
                 //   fail: (err) => {
                 //     console.error(err)
                 //   }
                 // })
                 wx.uploadFile({
                   url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
                   filePath: uploadFile,
                   name: 'file',
                   formData: {
                     'user': 'test'
                   },
                   success(res) {
                     const data = res.data
                     //do something
                   }
                 })
               },
               fail: (err) => {
                 console.error(err)
               }
             }, this)
           }, 500);
 
 
 
 
         }
       })
 
 
 
 
     }
   })

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值