小程序圖片轉base64


1:動態tabBar,item項,相冊或者手機拍照
clickPhoto() {
var that = this;
wx.showActionSheet({
itemList: ['從相冊中選擇', '拍照'],
itemColor: "#2874dc",
success: function (res) {
if (!res.cancel) {
if (res.tapIndex == 0) {
that.chooseWxImageShop('album'); // 從相冊中選擇

} else if (res.tapIndex == 1) {
that.chooseWxImageShop('camera'); // 手機拍照
}
}
}
})
},
 
2:用戶選擇圖片
chooseWxImageShop: function (type) {
var that = this;
wx.chooseImage({
count: 4, // 允許用戶選擇幾張圖片
sizeType: ['original', 'compressed'],
sourceType: [type],
success: function (res) {
var arr = that.data.photoArr.concat(res.tempFilePaths);
that.setData({
photoArr: arr
})

var imgArr = [];
if (arr.length != 0){
console.log('外層');
for (var i in arr) {
// 調函數圖片轉 base64
that.urlTobase64(arr[i]).then((res) => {
 
imgArr.push(res);
that.baseImgData.imgArr = imgArr;
 
})
.catch((res) => {
// app.setToast('請求失敗');
})
}
that.setData({
baseImgData: imgArr
})
}
},
fail: function (res) {
console.log('photo fail', res)
}
})
},
 
3:圖片轉base64傳臨時路徑
urlTobase64(url) {
  return new Promise((resolve, reject) => { // promise 解決異步問題
    wx.request({
      url: url,
      responseType: 'arraybuffer', //最關鍵的參數,設置返回的數據格式為arraybuffer
      success: (res) => {
        var base64 = wx.arrayBufferToBase64(res.data);
        base64 = 'data:image/jpeg;base64,' + base64;
        resolve(base64);
      },
      fail: (res) => {
        reject(false);
      }
    })
  })
},


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM