溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

微信小程序之批量上傳并壓縮圖片的實(shí)例代碼

發(fā)布時(shí)間:2020-09-14 19:37:47 來源:腳本之家 閱讀:490 作者:Jaiaxn 欄目:web開發(fā)

具體內(nèi)容如下所示:

首先,要在.wxml文件里面創(chuàng)建一個(gè)canvas,作用是承載壓縮的圖片,以供上傳的時(shí)候獲取

這個(gè)canvas不能隱藏,否則沒效果,可以將其移至屏幕外。

<canvas canvas-id='attendCanvasId' class='myCanvas'></canvas>

然后呢,就是.js文件里面的方法了

// 點(diǎn)擊加_壓縮
 takePhoto: function () {
  var that = this;
  let imgViewList = that.data.imgViewList; //這個(gè)是用來承載頁面循環(huán)展示圖片的
   //拍照、從相冊(cè)選擇上傳
   wx.chooseImage({
    count: 4,  //這個(gè)是上傳的最大數(shù)量,默認(rèn)為9
    sizeType: ['compressed'],  //這個(gè)可以理解為上傳的圖片質(zhì)量類型(官方給的),雖然沒什么卵用,要不然還要我們自己寫壓縮做什么
    sourceType: ['album', 'camera'],  //這個(gè)是圖片來源,相冊(cè)或者相機(jī)
    success: function (res) {
     var tempFilePaths = res.tempFilePaths  //這個(gè)是選擇后返回的圖片列表
     that.getCanvasImg(0, 0, tempFilePaths);  //進(jìn)行壓縮
    } 
   });
 },
 //壓縮并獲取圖片,這里用了遞歸的方法來解決canvas的draw方法延時(shí)的問題
 getCanvasImg: function (index,failNum, tempFilePaths){
  var that = this;
  if (index < tempFilePaths.length){
   const ctx = wx.createCanvasContext('attendCanvasId');
   ctx.drawImage(tempFilePaths[index], 0, 0, 300, 150);
   ctx.draw(true, function () {
    index = index + 1;//上傳成功的數(shù)量,上傳成功則加1
    wx.canvasToTempFilePath({
     canvasId: 'attendCanvasId',
     success: function success(res) {
      that.uploadCanvasImg(res.tempFilePath);
      that.getCanvasImg(index,failNum,tempFilePaths);
     }, fail: function (e) {
      failNum += 1;//失敗數(shù)量,可以用來提示用戶
      that.getCanvasImg(inedx,failNum,tempFilePaths);
     }
    });
   });
  }
 },
 //上傳圖片
 uploadCanvasImg: function (canvasImg){
  var that = this;
  let imgViewList = that.data.imgViewList;
  var tempImg = canvasImg;
  wx.uploadFile({
   url: app.d.fileServer,//文件服務(wù)器的地址
   filePath: tempImg,
   formData: {
    paramPath: "gift"
   },
   name: 'file',
   success: function (res) {
    var json2map = JSON.parse(res.data);
    imgViewList.push(app.d.imageUrlFix + json2map[0].fileUrl);
    that.setData({
     imgViewList: imgViewList,
    })
   }
  })
 },

總結(jié)

以上所述是小編給大家介紹的微信小程序之批量上傳并壓縮圖片的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI