背景:在做一個用戶上傳圖片(發布隨筆),但是微信需要對圖片進行驗黃等檢測,並規定圖片尺寸在750*1334,所以要對圖片進行等比例縮放。
(本來寫在后端合適,1.是后端懶,2.后端些了一個,有時候圖片尺寸大了,報內存不足,所以最后寫在了小程序端)
https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=11522142966rk3L2&version=1&lang=zh_CN&platform=2
這個寫在 wx.chooseImage 里面
//let that = this;//在外部定義 //打印未處理的圖片信息 wx.getFileInfo({ filePath: file.path, success: function (res) { console.log(res); } }) //-----壓縮圖片開始 (像素不超過750*1334) wx.getImageInfo({ src: file.path, success: function (res) { console.log(res); let cW = res.width, cH = res.height; let cWidth = cW,cHeight= cH; if ((cW / cH)<0.56){ //說明 要依高為縮放比例--0.56是 750/1334的結果 if (cH>1334){ cHeight = 1334; cWidth = (cW * 1334) / cH; } } else {//要依寬為縮放比例 if (cW > 750) { cWidth = 750; cHeight = (cH * 750) / cW; } } console.log(parseInt(cWidth));//計算出縮放后的寬 console.log(parseInt(cHeight));//計算出縮放后的高 that.setData({ cWidth: cWidth, cHeight: cHeight});//讓canvas大小和要縮放的圖片大小一致 let imageW = cWidth, imageH = cHeight, canvasId = "canvas", imagePath = res.path; const ctx = wx.createCanvasContext(canvasId); ctx.drawImage(imagePath, 0, 0, cW, cH, 0, 0, imageW, imageH); ctx.draw(false, setTimeout(function () { // 一定要加定時器,因為ctx.draw()應用到canvas是有個時間的 wx.canvasToTempFilePath({ canvasId: canvasId, x: 0, y: 0, width: imageW, height: imageH,
destWidth: imageW,
destHeight: imageH,
quality: 1, success: function (res) { console.log(res); //打印處理后的圖片信息 wx.getFileInfo({ filePath: res.tempFilePath, success: function (res) { console.log(res); } }) }, }); }, 200)); } }); //-----壓縮圖片結束
wxml 中要加
<canvas class="canvas" canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;"></canvas>
可以加些樣式隱藏
visibility: hidden;position:absolute;z-index:-1; left:-10000rpx;top:-10000rpx;
一個等比縮放的效果:

參考 :
https://www.cnblogs.com/jonyellow/p/11727776.html
https://github.com/jonyellow/code-diary/