使用 Express 渲染 Base64 PNG [英] Rendering a Base64 PNG with Express

查看:37
本文介绍了使用 Express 渲染 Base64 PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Node.js 服务器有如下内容:

My Node.js server has something that looks like the following:

app.get("/api/id/:w", function(req, res) {
    var data = getIcon(req.params.w);
});

这里,data 是一个包含 PNG 图像的 Base64 表示的字符串.有什么方法可以将它发送给访问路由的客户端,该路由被编码并显示为图像(例如,URL 可以在 img 标签中使用)?

Here, data is a string containing a Base64 representation of a PNG image. Is there any way I can send this to a client accessing the route encoded and displayed as an image (e.g. so the URL can be used in an img tag)?

推荐答案

是的,您可以对 base64 字符串进行编码并将其作为图像返回给客户端:

Yes you can encode your base64 string and return it to the client as an image:

server.get("/api/id/:w", function(req, res) {
    var data = getIcon(req.params.w);
    var img = Buffer.from(data, 'base64');

   res.writeHead(200, {
     'Content-Type': 'image/png',
     'Content-Length': img.length
   });
   res.end(img); 
});

这篇关于使用 Express 渲染 Base64 PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆