利用Canvas壓縮圖片

實(shí)現(xiàn)方法說(shuō)明:

1 調(diào)用wx.getImageInfo取得圖片原始寬高,計(jì)算輸出圖片寬高(限定短邊等比縮放)

2 調(diào)用ctx.drawImage用計(jì)算出的寬高把圖片畫(huà)到Canvas上,

3 調(diào)用wx.canvasToTempFilePath把Canvas上的畫(huà)面保存到文件.

其他說(shuō)明:

1 因?yàn)镃anvas使用的單位是px,手機(jī)設(shè)備上不是物理分辨率單位,需要調(diào)用wx.getSystemInfo取得pixelRatio用于計(jì)算基于px單位寬高.

2 為了調(diào)試方便,加入了getImageInfo函數(shù),正式使用時(shí)可以注銷掉.

3 因?yàn)槭褂昧薱anvas,小程序中不能做離屏Canvas操作.所以必須在wxml中加帶id的canvas標(biāo)簽

4 canvas的寬高必須滿足圖片的寬高,所以要在ctx.drawImage之前調(diào)用resizeCanvas

util.js中加

var sysInfo
const getSystemInfo = function () {
 return new Promise((resolve, reject) => {
   if (sysInfo) {
     resolve(sysInfo)
     return
   }
   wx.getSystemInfo({
     success: (info) => {
       console.debug('systemInfo', info)
       sysInfo = info
       resolve(info)
     },
     fail: reject
   })
 })
}
const getImageInfo = function (path) {
 var begin = new Date().getTime()
 return new Promise((resolve, reject) => {
   wx.getFileInfo({
     filePath: path,
     success: function (file) {
       wx.getImageInfo({
         src: path,
         success: function (image) {
           var info = {
             size: file.size,
             height: image.height,
             width: image.width,
             orientation: image.orientation,
             type: image.type,
             digest: file.digest,
             path: image.path,
             cost: (new Date().getTime() - begin),
           }
           console.debug('圖片info', info)
           resolve(info)
         },
         fail: reject,
       })
     },
     fail: reject,
   })
 })
}
/**
* @Param {String} path 圖片路徑
* @Param {String} canvas 定義在canvas標(biāo)簽的id
* @Param {Function} resize 用于修canvas的寬高
* @Param {Number} limit 短邊限制值
*/
const compress = function (path, canvas, resize, limit) {
 console.debug('開(kāi)始?jí)嚎s', { path: path, canvas: canvas })
 if (!limit) {
   limit = 1440
 }
 return getSystemInfo().then((sysInfo) => {
   return new Promise((resolve, reject) => {
     wx.getImageInfo({
       src: path,
       success: function (info) {
         console.debug('原圖信息', info)
         if (Math.min(info.width, info.height) <= 1440) {
           resolve(path)
           return
         }
         var width = limit
         var height = limit * info.height / info.width
         if (info.width > info.height) {
           height = limit
           width = limit * info.width / info.height
         }
         if (sysInfo.brand != 'devtools') {
           width = width / sysInfo.pixelRatio
           height = height / sysInfo.pixelRatio
         }
         resize(width, height, function () {
           compressImage(canvas, path, width, height)
             .then(resolve)
             .catch(reject)
         });
       },
       fail: reject
     })
   })
 })
}
const compressImage = (canvas, path, width, height) => {
 var begin = new Date().getTime()
 return new Promise((resolve, reject) => {
   const ctx = wx.createCanvasContext(canvas)
   ctx.drawImage(path, 0, 0, width, height)
   ctx.draw(false, function () {
     wx.canvasToTempFilePath({
       width: width,
       height: height,
       fileType: 'jpg',
       quality: 0.7,
       canvasId: canvas,
       success: function (res) {
         console.debug('壓縮圖片cost:' + (new Date().getTime() - begin))
         resolve(res.tempFilePath)
         getImageInfo(res.tempFilePath)
       },
       fail: reject
     })
   })
 })
}
/**
* @Param {String} canvasId 定義在canvas標(biāo)簽的id
* @Param {Function} resizeHandler 用于修改canvas的寬高
*/
const chooseImage = function (canvasId, resizeHandler) {
 return new Promise((resolve, reject) => {
   wx.chooseImage({
     sizeType: ['original'],
     sourceType: ['camera'],
     success: (res) => {
       compress(res.tempFilePaths[0], canvasId, resizeHandler)
         .then(resolve)
         .catch(reject)
     },
     fail: reject
   })
 })
}

使用方法

頁(yè)面js文件

appendImage: function (e) {
 util.chooseImage('compressCanvas', this.resizeCanvas)
   .then((path) => {
     this.setData({
       files1: this.data.files1.concat(path),
       dirty: true,
     });
   })
},
resizeCanvas: function (width, height, callback) {
 this.setData({
   canvasWidth: width,
   canvasHeight: height,
 }, callback)
},

頁(yè)面wxml文件

<view style="width:0px;height:0px;overflow:hidden;position:absolute;left:750rpx">
 <canvas canvas-id="compressCanvas" style="width:{{canvasWidth}}px; height:{{canvasHeight}}px" />
view>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容