将缓冲区数据转换为图像 [英] Convert buffer data to an image
问题描述
我如何将该缓冲区数据转换为图像,所以当循环遍历结果并将其呈现在img src中时,它将呈现为用户可以看到的图像
how do i convert this buffer data to an image so when am looping thru the result and rendering it in the img src it will render as an image that the user can see
使用ejs渲染
<span>
<img class="user-with-avatar" src=<%=item.photo%> />
</span>
当我console.log(result.data.photo)时,我得到了
when i console.log(result.data.photo), i get this
{"type":"Buffer","data":[100,97,116,97,58,14,79,8,113,97,65,43,57,55,89,69,88,51,66,101,70,86,112,121,112,121,121,121,80,81,104]},
{"type":"Buffer","data":[100,97,116,97,58,14,79,8,113,97,65,43,57,55,89,69,88,51,66,101,70,86,112,121,112,121,121,121,80,81,104]},
{"type":"Buffer","data":[100,97,116,97,58,14,79,8,113,97,65,43,57,55,89,69,88,51,66,101,70,86,112,121,112,121,121,121,80,81,104]}
我如何通过这种代码安排对其进行修复
how do i fix it with this code arrangement
app.get('/products', function (req, res) {
if (req.session.token && req.session.user_id) {
let data = {
token: req.session.token,
id: req.session.user_id,
}
let url = `https:/url/product/get_products?id=${data.id}&token=${data.token}`
functions.callAPIGet(
url,
function (error, result) {
res.render('products', {
result: result.data
})
}
);
} else {
res.redirect('/login')
}
});
推荐答案
您需要将缓冲区转换为base64字符串.这是一个PNG图片的示例.我不清楚您的图像的存储位置和格式.本示例将图像读取为文件.可能需要根据您的数据源进行调整.
You'll need to convert the buffer to a base64 string. Here's an example for a PNG image. I am not clear on where your image is stored and format it's in however. This example reads the image as a file. May need to adjust things based on your data source.
server.js
const express = require('express')
const app = express()
const fs = require('fs')
app.set('view engine', 'ejs')
app.get('/', function(req, res) {
const data = fs.readFileSync('./image.png')
res.render('page', {
image: data.toString('base64')
})
})
const server = app.listen(2000)
视图/page.ejs
<img src="data:image/png;base64,<%= image %>" />
这篇关于将缓冲区数据转换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!