Node.js从web获取图像并使用base64进行编码

时间:2013-06-15 13:14:49

标签: node.js encoding express base64

我正在尝试从网络上获取图片并使用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);
    }
});

这似乎与解决方案非常接近,但我无法让它发挥作用。它识别数据类型并给出输出:

data:image/png;base64

然而缓冲列表'bl'似乎是空的。

提前致谢!

9 个答案:

答案 0 :(得分:112)

BufferList已过时,因为其功能现在位于Node核心中。这里唯一棘手的部分是设置请求不使用任何编码:

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

答案 1 :(得分:15)

最新消息,2017年结束

嗯,在阅读了上述答案和一些研究之后,我开始了解 不需要任何软件包安装的新方法 ,{{1}模块(内置)就足够了!

注意:我在节点版本6.x中使用过它,所以我猜它也适用于以上版本。

http

我希望它有所帮助!

另外,请详细了解var http = require('http'); http.get('http://tinypng.org/images/example-shrunk-8cadd4c7.png', (resp) => { resp.setEncoding('base64'); body = "data:" + resp.headers["content-type"] + ";base64,"; resp.on('data', (data) => { body += data}); resp.on('end', () => { console.log(body); //return res.json({result: body, status: 'success'}); }); }).on('error', (e) => { console.log(`Got error: ${e.message}`); }); here

答案 2 :(得分:8)

您可以使用base64-stream Node.js模块,它是一个流式Base64编码器/解码器。这种方法的好处是你可以转换图像,而无需将整个事物缓冲到内存中,也不需要使用请求模块。

var http = require('http');
var base64encode = require('base64-stream').Encode;

http.get('http://tinypng.org/images/example-shrunk-8cadd4c7.png', function(res) {
    if (res.statusCode === 200)
        res.pipe(base64encode()).pipe(process.stdout);
});

答案 3 :(得分:4)

如果在使用axios作为http客户端时遇到任何相同的问题,解决方案是将responseType属性添加到请求选项中,其值为'arraybuffer':

let image = await axios.get('http://aaa.bbb/image.png', {responseType: 'arraybuffer'});
let returnedB64 = Buffer.from(image.data).toString('base64');

希望这会有所帮助

答案 4 :(得分:3)

如果您使用的是 axios,那么您可以按照以下步骤操作

var axios = require('axios');
const url ="put your url here";
const image = await axios.get(url, {responseType: 'arraybuffer'});
const raw = Buffer.from(image.data).toString('base64');
const base64Image = "data:" + image.headers["content-type"] + ";base64,"+raw;

您可以使用解码 base64 进行检查。

答案 5 :(得分:1)

我用于加载并将图像编码到base64字符串node-base64-image npm模块中。

下载并编码图像:

var base64 = require('node-base64-image');

var options = {string: true};
base64.base64encoder('www.someurl.com/image.jpg', options, function (err, image) {
    if (err) {
        console.log(err);
    }
    console.log(image);
});

对本地图像进行编码:

var base64 = require('node-base64-image');

var path = __dirname + '/../test.jpg',
options = {localFile: true, string: true};
base64.base64encoder(path, options, function (err, image) {  
    if (err) { console.log(err); }  
    console.log(image);  
}); 

答案 6 :(得分:1)

另一种使用节点获取的方法,它分解了每个变量的步骤:

const fetch = require('node-fetch');

const imageUrl = "Your URL here";
const imageUrlData = await fetch(imageUrl);
const buffer = await imageUrlData.buffer();
const contentType = await imageUrlData.headers.get('content-type');
const imageBas64 = 
`data:image/${contentType};base64,`+buffer.toString('base64');

答案 7 :(得分:0)

如果您知道图像类型,则它与node-fetch包一起使用。可能不适合每个人,但我已经将node-fetch作为依赖项,因此,以防其他人陷入类似困境:

await fetch(url).then(r => r.buffer()).then(buf => `data:image/${type};base64,`+buf.toString('base64'));

答案 8 :(得分:0)

单线:

Buffer.from(
    (
      await axios.get(image, {
      responseType: "arraybuffer",
    })
  ).data,
  "utf-8"
).toString("base64")