Node.js的从网页和连接$ C $获得图象C使用Base64 [英] Node.js get image from web and encode with base64
本文介绍了Node.js的从网页和连接$ C $获得图象C使用Base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从网络和连接code它的base64获取的图像。
I'm trying to fetch an image from the web and encode it with base64.
我至今基本上是:
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);
}
});
这似乎是pretty接近解决方案,但我不能完全得到它的工作。它识别的数据类型和给出的输出:
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
不过bufferlist'BL'似乎是空的。
however the bufferlist 'bl' seems to be empty.
在此先感谢!
推荐答案
BufferList已经过时,因为它现在的功能是节点的核心。这里唯一棘手的部分是设置请求不使用任何编码方式:
BufferList is obsolete, as it's 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," + new Buffer(body).toString('base64');
console.log(data);
}
});
这篇关于Node.js的从网页和连接$ C $获得图象C使用Base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文