前端imageBuffer设置图片src(后端到前端直传buffer)
本质为buffer转base64
let bytes = new Uint8Array(imageBuffer.data); let data = ""; let len = bytes.byteLength; for (let i = 0; i < len; i++) { data += String.fromCharCode(bytes[i]); } image.src = "data:image/png;base64," + window.btoa(data);
微信小程序的url图片到buffer再到base64
urlTobase64(url){ wx.request({ url:url, responseType: 'arraybuffer', //最关键的参数,设置返回的数据格式为arraybuffer success:res=>{ //把arraybuffer转成base64 let base64 = wx.arrayBufferToBase64(res.data); //不加上这串字符,在页面无法显示的哦 base64 = 'data:image/jpeg;base64,' + base64 //打印出base64字符串,可复制到网页校验一下是否是你选择的原图片呢 console.log(base64) } }) }
=======下面一个例子,通过建立小程序云函数,再云调用,获取小程序码,
1.建立云函数:unlimitQR (3个文件)
index.js内容--其他保持默认就行
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init() // 云函数入口函数 exports.main = async (event, context) => { const wxContext = cloud.getWXContext(); try { const result = await cloud.openapi.wxacode.getUnlimited({ scene: 'a=1' }) console.log(result); return result } catch (err) { console.log(err) return err } }
2.在随便一个页面测试 云函数,云调用下.
let that = this; wx.cloud.callFunction({ // 需调用的云函数名 name: 'unlimitQR', // 传给云函数的参数 (具体要传字符传还是json 要看小程序手册) data: { a: 12, b: 19, }, // 成功回调 complete(res) { let buffer = res.result.buffer; console.log(buffer); const base64 = wx.arrayBufferToBase64(buffer) let bb = "data:image/png;base64,"+base64; that.setData({bb:bb}); } })
把bb字符串设置到image标签的src上.
转:
https://blog.csdn.net/qq_36875339/article/details/81086205 (小程序图片转Base64,方法总结)
https://blog.csdn.net/u010081689/article/details/51088068 (node使用buffer生成图片)
https://www.cnblogs.com/brainworld/p/8330334.html (前端imageBuffer设置图片src)