【微信小程序】圖片壓縮-純質量壓縮,非長寬裁剪壓縮

原理:利用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, 結束, 👏

相關文章
相關標籤/搜索