在微信小程序的開發過程,經常會使用自帶的api(wx.chooseImage)進行圖片拍照或選擇圖片進行上傳,有時圖片太大,造成上傳和下載時過慢,現對圖片進行壓縮后上傳,以下是流程和代碼
一、小程序的版本選擇了3.2.5,使用其它版本有時不知道錯誤
二、wxml代碼,需要添加canvas
<canvas?style="width:?{{cwidth}}px;height:?{{cheight}}px;position:fixed;top:9999px"?canvas-id="mycanvas"></canvas>
三、js代碼
1、參數
?cwidth:'375',
cheight:'667',
???//上傳圖片時,當前數組下標,用來確認上傳第幾張圖片,上傳完一次就+1
????????tempNum:?0,
????????//?圖片上傳參數
????????filePath:?"",
????????images:?[],
????????count:?1,
2、選擇圖片wx.chooseImage
?
// 選擇圖片chooseImage: function (e) {console.log('選擇圖片chooseImage')var that = this;wx.chooseImage({count: that.data.count, // 默認9sizeType: ['compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有sourceType: ['camera'], // 可以指定來源是相冊還是相機,默認二者都有success: function (res) {console.log('圖片大小='+res.tempFiles[0].size)if(res.tempFiles[0].size>500000){//圖片大于500K才進行壓縮,壓縮后大約400Kthat.canvasImage(res.tempFilePaths[0], 0) } else{//圖片添加水印that.addTimeWatermark(res.tempFilePaths[0])} },})},//壓縮圖片canvasImage:function(imgUrl,index){console.log('canvasImage壓縮圖片')wx.showLoading({title: '照片上傳中...',})var that = thiswx.getImageInfo({src: imgUrl,success(res) {console.log("路徑", res.path)console.log('獲得原始圖片大小', res.width, res.height)var originWidth, originHeight;originHeight = res.height;originWidth = res.width;// 最大尺寸限制 //壓縮比例var maxWidth = originWidth >= originHeight ? 540 : 810,maxHeight = originWidth >= originHeight ? 810 : 540;// 目標尺寸var targetWidth = originWidth,targetHeight = originHeight;//等比例壓縮,如果寬度大于高度,則寬度優先,否則高度優先if (originWidth > maxWidth || originHeight > maxHeight) {if (originWidth / originHeight > maxWidth / maxHeight) {// 要求寬度*(原生圖片比例)=新圖片尺寸targetWidth = maxWidth;targetHeight = Math.round(maxWidth * (originHeight / originWidth));} else {targetHeight = maxHeight;targetWidth = Math.round(maxHeight * (originWidth / originHeight));}}console.log("壓縮后的圖片大小", targetWidth, targetHeight)var ctx = wx.createCanvasContext('mycanvas');ctx.clearRect(0, 0, targetWidth, targetHeight);ctx.drawImage(res.path, 0, 0, targetWidth, targetHeight);ctx.draw();//更新canvas大小that.setData({cwidth: targetWidth,cheight: targetHeight});setTimeout(function () {wx.canvasToTempFilePath({canvasId: 'mycanvas',success: (res) => {wx.hideLoading()console.log("壓縮后的臨時路徑:", res.tempFilePath)that.addTimeWatermark(res.tempFilePath)},fail: (err) => {wx.hideLoading()console.error(err)}}, this)}, 400); //延遲400毫秒為了等canvas畫上}})},
// 添加時間水印addTimeWatermark: function (imagePath) {var that = thisconsole.log('addTimeWatermark=' + imagePath)var ctx = wx.createCanvasContext('mycanvas');this.roundRectColor(ctx, 0, 30, 375, 620, 16);ctx.drawImage(imagePath, 15, 120, 344, 400);ctx.save();// 設置水印文字const time = app.util.formatTime()console.log('time=' + time)ctx.beginPath(); //開始繪制 ctx.setFontSize(22);ctx.setFillStyle('#DC3545')ctx.fillText(time, 15, 450); // 根據實際情況調整位置ctx.draw();//將生成好的圖片保存到本地,需要延遲一會,繪制期間耗時setTimeout(function () {wx.canvasToTempFilePath({canvasId: 'mycanvas',success: function (res) {var tempFilePath = res.tempFilePath;console.log('imagePath=' + tempFilePath)that.data.images.push(tempFilePath);console.log(that.data.images)that.setData({imagePath: tempFilePath,images: that.data.images});},fail: function (res) {console.log(res);}});}, 200);},roundRectColor: function (context, x, y, w, h, r) { //繪制圓角矩形(純色填充)context.save();context.setFillStyle("#FFFFFF"); //小框context.setStrokeStyle('#FFFFFF') //大框// context.setLineJoin('round'); //交點設置成圓角context.setLineWidth(r);context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);context.fillRect(x + r, y + r, w - r * 2, h - r);context.stroke();context.closePath();},
//上傳圖片
app.util.uploadImg(that.callBackClose, app, that.data.pid, that.data.images, that.data.tempNum, 'check')