在开发微信小程序中,如何做好图片纯质量压缩?

【春哥博客技术教程分享】在开发微信小程序过程中免不了经常遇到图片的处理,如何做好图片压缩,非长宽裁剪压缩呢?下面春哥团队大东和大家分享下教程,主要原理是利用canvas来实现,将图片绘制到canvas上,然后canvas转图片时,微信提供的一个方法wx.canvasToTempFilePath(Object object, Object this),此方式可以指定生成图片的质量,下图是从官方API截的图:

在开发<a href=https://www.cgtblog.com/e/tags/?tagid=1079 target=_blank class=infotextkey>微信小程序</a>中,如何做好图片纯质量压缩?

其中quality可以指定图片的质量,quality的值越小,图片越模糊,通过此方法可以实现图片的压缩

注意:

1.quality设置只对jpg格式的图片有效,使用时要将fileType设置为“jpg”, 此举可能会导致其它格式的图片变为jpg格式 2.透明背景的png图片,绘制到canvas上使用此方式导出的图片是黑色背景,有需求的话是需要canvas先设置背景色的,请小伙伴们注意爬坑。

有了这个参数,压缩就简单很多了,下面是代码:

wxml

<view>
  <button bindtap="chooseImage">选择图片</button>
</view>

<!-- 展示压缩后的图片 -->
<view style="display: flex;justify-content: center;flex-direction: column">
  <image width="50" mode="widthFix" src="{{imagePath}}"></image>
</view>

<button wx:if="{{imagePath.length>0}}" bindtap="save">点击下载压缩后的图片</button>

<!-- 用来渲染的canvas --> 
<canvas canvas-id='attendCanvasId' class='myCanvas' style='width:{{cWidth}}px;height:{{cHeight}}px;position: fixed;top: -9999px;left: -9999px;'></canvas>

js

Page({
  data: {
    imagePath: '',
    quality: 0.2
  },
  onLoad: function (options) {
  
  },
  /**
  * 选项添加图片事件
  */
  chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: result => {
        wx.getImageInfo({
          src: result.tempFilePaths[0],
          success: function (res) {
            that.setData({
              cWidth: res.width,
              cHeight: res.height
            })
            that.getCanvasImg(result.tempFilePaths, res.width, res.height, that.data.quality, function (res) {
              that.setData({
                imagePath: res.tempFilePath
              });
            });
          }
        })
      }
    })
  },
  /**
   * 质量压缩
   */
  getCanvasImg(tempFilePaths, canvasWidth, canvasHeight, quality, callback) {
    var that = this; 
    const ctx = wx.createCanvasContext('attendCanvasId');
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    ctx.drawImage(tempFilePaths[0], 0, 0, canvasWidth, canvasHeight);
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'attendCanvasId',
        fileType: 'jpg',
        quality: quality,
        success: function success(res) {
          callback && callback(res)
        }, fail: function (e) {
          wx.showToast({
            title: '图片上传失败,请重新上传!',
            icon: 'none'
          })
        }
      });
    });
  },
  /**
   * 图片保存到相册
   */
  save(e) {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success: function (res) {
        console.log('图片已保存');
      },
      fail: function (res) {
        console.log('保存失败');
      }
    })
  },
})

注意点

注意设置canvas-id='attendCanvasId' canvas要离屏渲染,就是移出屏幕之外,但是元素还是显示的,position: fixed;top: -9999px;left: -9999px; 不能使用 display: none; 这样是获取不到canvas元素的。

最后

h5页面中也有提供这样的方法

在开发<a href=https://www.cgtblog.com/e/tags/?tagid=1079 target=_blank class=infotextkey>微信小程序</a>中,如何做好图片纯质量压缩?

例如这样子:

let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); ctx.drawImage(imagePath, 0, 0, w, h); canvas.toDataURL('image/jpeg', quality);

需要的小伙伴可以学习起来,如果有更多开发心得欢迎到春哥技术源码论坛交流、分享。

 



来源:春哥技术博客,欢迎分享,转载请注明出处。(欢迎加春哥团队客服微信号:taike668)

本文地址:https://www.cgtblog.com/wx/3682.html
上一篇:老司机教你如何避开组件cover-view的      下一篇:小程序云开发如何实现管理员通知消息