微信小程序中,要把圖片縮小再上傳,可使用畫布組件(canvas)縮小圖片。在 wxml 代碼中定義畫布,位置應在屏幕外,這樣就像是在后台處理圖片。wxml 文件中的 canvas 代碼:
<view style="width:0px;height:0px;overflow:hidden;"> <canvas canvas-id="canvasid1" style="width:600px;height:600px;position:absolute;top:-800px;left:-800px;border:1px solid blue;"></canvas> </view>
這段代碼可處於 wxml 文件的末尾處。
要處理的圖片不止一張,在縮小圖片的代碼中,用遞歸調用方式:
function resize_recursion() { // canvas : resize ctx1.drawImage(arr1[i].file, 0, 0, arr1[i].widthx, arr1[i].heightx) ctx1.draw(false, res => { var lca = wx.canvasToTempFilePath({ x: 0, y: 0, width: arr1[lncnt].widthx, height: arr1[i].heightx, canvasId: 'canvasid1', quality: 1, success: res => { arr1[i].file1 = res.tempFilePath i = i + 1 if(i==arr1.length){ lca = uploadproc() return }else{ return resize_recursion() } }, fail: function (err) { console.log(err) } }) }) // end of draw }
上傳圖片用到 js 的 Promise對象,提高傳輸效率:
var arrPromise1 = new Array() for (i = 0; i < arr1.length; i++) { arrPromise1.push(new Promise(function (resolve, reject) { wx.cloud.uploadFile({ cloudPath: arr1[i].file1, filePath: arr1[i].file2, success: res => { resolve(res) }, fail: error => { reject(error) } }) })) } Promise.all(arrPromise1).then(res => { for (var i = 0; i < res.length; i++) { arr1[i].upfileId = res[i].fileID } }
圖片文件最初來自交互操作:wx.chooseimage(),選定的圖片存放在數組arr1中。然后讀取圖片的尺寸,根據大小來決定是否需要執行縮小代碼。這是讀取圖片大小的代碼,也用到 js 的 Promise對象:
var arrPromise1 = new Array() for (i = 0; i < arr1.length; i++) { arr1[i] = { "file": arr1[i].path, "file1": '', "upfileId": '', "size": arr1[i].size, "width1": 0, "height1": 0, "widthx": 0, "heightx": 0, "flag": 0, "idx1": 0 } arrPromise1.push(new Promise(function (resolve, reject) { wx.getImageInfo({ src: arr1[i].file, success: res => { resolve(res) }, fail: error => { reject(error) } }) })) } Promise.all(arrPromise1).then(res => { for (i = 0; i < res.length; i++) { arr1[i].width1 = res[i].width arr1[i].height1 = res[i].height arr1[i].widthx = 200 arr1[i].heightx = 350 arr1[i].flag = lca.flagx arr1[i].idx1 = i } }, function (res) { console.log('promiseerr') })
整個過程中,讀取圖片大小和上傳可以用 Promise對象,縮小圖片因為要用畫布組件而無法使用Promise。[END]