Node.js 从网络获取图像并使用 base64 进行编码 [英] Node.js get image from web and encode with base64
本文介绍了Node.js 从网络获取图像并使用 base64 进行编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从网络中获取图像并使用 base64 对其进行编码.
I'm trying to fetch an image from the web and encode it with base64.
到目前为止我所拥有的基本上是:
what i have so far is basically:
var request = require('request');
var BufferList = require('bufferlist').BufferList;
bl = new BufferList(),
request({uri:'http://tinypng.org/images/example-shrunk-8cadd4c7.png',responseBodyStream: bl}, function (error, response, body)
{
if (!error && response.statusCode == 200)
{
var type = response.headers["content-type"];
var prefix = "data:" + type + ";base64,";
var base64 = new Buffer(bl.toString(), 'binary').toString('base64');
var data = prefix + base64;
console.log(data);
}
});
这似乎非常接近解决方案,但我无法让它发挥作用.它识别数据类型并给出输出:
This seems to be pretty close to the solution but i can't quite get it to work. It recognizes the data type and gives out the output:
data:image/png;base64
但是缓冲区列表 'bl' 似乎是空的.
however the bufferlist 'bl' seems to be empty.
提前致谢!
推荐答案
BufferList 已过时,因为其功能现在位于 Node 核心中.这里唯一棘手的部分是设置请求不使用任何编码:
BufferList is obsolete, as its functionality is now in Node core. The only tricky part here is setting request not to use any encoding:
var request = require('request').defaults({ encoding: null });
request.get('http://tinypng.org/images/example-shrunk-8cadd4c7.png', function (error, response, body) {
if (!error && response.statusCode == 200) {
data = "data:" + response.headers["content-type"] + ";base64," + Buffer.from(body).toString('base64');
console.log(data);
}
});
这篇关于Node.js 从网络获取图像并使用 base64 进行编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文