微信小程序开发:缩小图片并上传

微信小程序中,要把图片缩小再上传,可使用画布组件(canvas)缩小图片。在 wxml 代码中定义画布,位置应在屏幕外,这样就像是在后台处理图片。wxml 文件中的 canvas 代码:

   <view >
     <canvas canvas- ></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]