将缓冲区数据转换为图像

时间:2020-02-27 23:50:18

标签: javascript node.js express ejs

我如何将该缓冲区数据转换为图像,所以当循环遍历结果并将其呈现在img src中时,它将呈现为用户可以看到的图像

am使用ejs进行渲染

     <span>
        <img class="user-with-avatar" src=<%=item.photo%> />
     </span>

当我console.log(result.data.photo)时,我得到了

{"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]}

我如何通过这种代码安排对其进行修复


    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')
            }
        });

1 个答案:

答案 0 :(得分:2)

您需要将缓冲区转换为base64字符串。这是PNG图片的示例。我不清楚您的图像的存储位置和格式。本示例将图像读取为文件。可能需要根据您的数据源进行调整。

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 %>" />