1. 程式人生 > >微信小程式:利用canvas縮小圖片

微信小程式:利用canvas縮小圖片

功能分兩部分:展示、提交
一期的時候,使用者預覽圖片,直接提交到後臺。但是發現如果圖片太大,還要進行二次處理,還會降低介面相應速度等原因。所以要對圖片進行壓縮。

壓縮原理:選擇圖片後,利用canvas的drawImage方法重新定義圖片大小,再利用canvasToTempFilePath方法下載到縮小後圖片。

// 利用絕對定位 隱藏canvas
<canvas canvas-id="photo_canvas" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position: absolute;left:-300px;top:-300px;"
>
</canvas>
wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: function (photo) {
        wx.getImageInfo({
          src: photo.tempFilePaths[0],
          success: function(res){
            var ctx = wx.createCanvasContext('photo_canvas');
            var ratio = 2
; var canvasWidth = res.width var canvasHeight = res.height; // 保證寬高均在200以內 while (canvasWidth > 200 || canvasHeight > 200){ //比例取整 canvasWidth = Math.trunc(res.width / ratio) canvasHeight = Math.trunc(res.height / ratio) ratio++; } _this.setData({ canvasWidth: canvasWidth, canvasHeight: canvasHeight })//設定canvas尺寸
ctx.drawImage(photo.tempFilePaths[0], 0, 0, canvasWidth, canvasHeight) ctx.draw() //下載canvas圖片 setTimeout(function(){ wx.canvasToTempFilePath({ canvasId: 'photo_canvas', success: function (res) { console.log(res.tempFilePath) }, fail: function (error) { console.log(error) } }) },100) }, fail: function(error){ console.log(error) } }) }, error: function (res) { console.log(res); } })