【微信小程序】图片压缩-纯质量压缩,非长宽裁剪压缩

原理:利用canvas来实现,将图片绘制到canvas上,而后canvas转图片时,微信提供的一个方法wx.canvasToTempFilePath(Object object, Object this),此方式能够指定生成图片的质量,下图是从官方API截的图:canvas

其中quality能够指定图片的质量,quality的值越小,图片越模糊,经过此方法能够实现图片的压缩bash

注意微信

1.quality设置只对jpg格式的图片有效,使用时要将fileType设置为“jpg”, 此举可能会致使其它格式的图片变为jpg格式

2.透明背景的png图片,绘制到canvas上使用此方式导出的图片是黑色背景,有需求的话是须要canvas先设置背景色的,请小伙伴们注意爬坑。
复制代码

有了这个参数,压缩就简单不少了,下面是代码:flex

wxmlui

<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>
复制代码

jsthis

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('保存失败');
      }
    })
  },
})
复制代码

注意点spa

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

最后code

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

例如这样子:xml

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

须要的小伙伴也能够本身研究研究哈...

ok, 结束, 👏

相关文章
相关标签/搜索