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

问题描述 投票:0回答:11

我正在尝试从网络获取图像并使用 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”似乎是空的。

node.js encoding express base64
11个回答
186
投票

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

58
投票

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

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

希望这有帮助


43
投票

嗯,在阅读了上面的答案和一些研究后,我知道了一种新方法,不需要安装任何软件包

http
模块(内置)就足够了!

注意:我已经在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}`);
});

希望对你有帮助!

此外,请查看更多有关

http.get(...)
这里


23
投票

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

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

const imageUrl = "Your URL here";
const imageUrlData = await fetch(imageUrl);
const buffer = await imageUrlData.arrayBuffer();
const stringifiedBuffer = Buffer.from(buffer).toString('base64');
const contentType = imageUrlData.headers.get('content-type');
const imageBase64 = 
`data:${contentType};base64,${stringifiedBuffer}`;

16
投票

如果您知道图像类型,它是带有

node-fetch
包的单行文本。可能不适合所有人,但我已经有
node-fetch
作为依赖项,所以以防万一其他人也有类似的情况:

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

12
投票

如果您使用的是 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来检查。


9
投票

您可以使用 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
投票

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

下载并编码图像:

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

2
投票

单行:

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

2
投票

旧帖子,但可以帮助别人。 基于对我有帮助的 Dmytro 回复。

const base64FromUrl = async (url: string) => {
  try {
    return Buffer.from((await axios.get(url, { responseType: "arraybuffer", })).data, "utf-8").toString("base64")
  } catch (error) {
    return ""
  }
}

我刚刚添加了错误处理。


0
投票

您可以使用 image-to-base64 Node.js 模块

使用此模块的好处是您可以轻松转换图像

const imageToBase64 = require('image-to-base64');

const imageLink = 'Your image link'
imageToBase64(imageLink);
.then((response) => {
    const base64Image = `data:image/png;base64,${response}`
    console.log(base64Image);
  })
  .catch((error) => {
    console.log(error);
  })

© www.soinside.com 2019 - 2024. All rights reserved.