图片上传要用到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上图片需要翻转
原文地址:https://www.cnblogs.com/guokeqiufeng/p/9585043.html
时间: 2024-11-06 03:52:15