圖片上傳要用到upng.js
const self = this
const ctx = wx.createCanvasContext('myCanvas')
const platform = wx.getSystemInfoSync().platform
const imgWidth = 60, imgHeight = 60;
wx.chooseImage({
success: res => {
//生成的圖片臨時路徑畫成canvas
ctx.drawImage(res.tempFilePaths[0], 0, 0, imgWidth, imgHeight)
ctx.draw(false, () => {
self.drawFinish = true
wx.canvasGetImageData({
canvasId: 'myCanvas',
x: 0,
y: 0,
width: imgWidth,
height: imgHeight,
success: res => {
if (platform === 'ios') {
// 兼容處理:ios獲取的圖片上下顛倒
res = this.reverseImgData(res)
}
// 3. png編碼
let pngData = upng.encode([res.data.buffer], res.width, res.height)
// 4. base64編碼
let base64 = wx.arrayBufferToBase64(pngData)
debugger
console.log('data:image/jpeg;base64,' + base64)
this.setData({
avatarUrl: 'data:image/jpeg;base64,' + base64
});
},
fail(res) {
debugger
console.log(res)
},
})
})
}
})
這里要有幾個坑
1.canvas那個標簽如果隱藏,會出現轉base64失敗的情況
2.ios上圖片需要翻轉