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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17124053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:47:58  来源:igfitidea点击:

Node.js get image from web and encode with base64

node.jsencodingexpressbase64

提问by Aleksr9

I'm trying to fetch an image from the web and encode it with base64.

我正在尝试从网络中获取图像并使用 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

however the bufferlist 'bl' seems to be empty.

但是缓冲区列表 'bl' 似乎是空的。

Thanks in advance!

提前致谢!

回答by Dan Kohn

BufferList is obsolete, as its functionality is now in Node core. The only tricky part here is setting request not to use any encoding:

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," + Buffer.from(body).toString('base64');
        console.log(data);
    }
});

回答by Ankur Shah

LATEST, AS OF 2017 ENDING

最新,截至 2017 年结束

Well, after reading above answers and a bit research, I got to know a new way which doesn't require any package installation, httpmodule(which is built-in) is enough!

好吧,在阅读了上面的答案并进行了一些研究之后,我知道了一种不需要任何软件包安装的新方法,http模块(内置)就足够了!

NOTE: I have used it in node version 6.x, so I guess its also applicable to above versions.

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

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

I hope it helps!

我希望它有帮助!

Also, check more about the http.get(...)here!

另外,请查看更多关于http.get(...)这里的信息

回答by Yehuda

If anyone encounter the same issue while using axios as the http client, the solution is to add the responseType property to the request options with the value of 'arraybuffer':

如果有人在使用 axios 作为 http 客户端时遇到同样的问题,解决方案是将 responseType 属性添加到值为“arraybuffer”的请求选项中:

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

Hope this helps

希望这可以帮助

回答by Ross J

You can use the base64-streamNode.js module, which is a streaming Base64 encoder / decoder. The benefit of this method is that you can convert the image without having to buffer the whole thing into memory, and without using the request module.

您可以使用base64-streamNode.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);
});

回答by Ross J

If you know the image type, it's a one-liner with the node-fetchpackage. Might not suit everyone, but I already had node-fetchas a dependency, so in case others are in a similar boat:

如果您知道图像类型,则它是带有node-fetch包装的单衬纸。可能不适合所有人,但我已经有了node-fetch依赖,所以如果其他人也有类似的情况:

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

回答by webmato

I use for load and encode image into base64 string node-base64-imagenpm module.

我用于将图像加载并编码为 base64 字符串node-base64-imagenpm 模块。

Download and encode an image:

下载并编码图像:

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

Encode a local 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);  
});