小程序 图片转base64然后上传的坑点
时间:2018-09-04 17:07:04
收藏:0
阅读:1818
图片上传要用到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上图片需要翻转
评论(0)