Node.js get image from web and encode with base64

node.jsEncodingExpressBase64

node.js Problem Overview


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

however the bufferlist 'bl' seems to be empty.

Thanks in advance!

node.js Solutions


Solution 1 - node.js

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

Solution 2 - node.js

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':

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

Hope this helps

Solution 3 - node.js

LATEST, AS OF 2017 ENDING

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

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

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 !

Solution 4 - node.js

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

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

Solution 5 - node.js

You can use the base64-stream Node.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.

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

Solution 6 - node.js

If you are using axios then you can follow below steps

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;

you can check with decode base64.

Solution 7 - node.js

Another way of using node fetch, which breaks down the steps per variable:

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 imageBas64 = 
`data:image/${contentType};base64,${stringifiedBuffer}`;

Solution 8 - node.js

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

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

Solution 9 - node.js

Oneliner:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAleksr9View Question on Stackoverflow
Solution 1 - node.jsDan KohnView Answer on Stackoverflow
Solution 2 - node.jsYehudaView Answer on Stackoverflow
Solution 3 - node.jsAnkur ShahView Answer on Stackoverflow
Solution 4 - node.jsuser993683View Answer on Stackoverflow
Solution 5 - node.jsRoss JView Answer on Stackoverflow
Solution 6 - node.jsVishwaView Answer on Stackoverflow
Solution 7 - node.jsNick TarasView Answer on Stackoverflow
Solution 8 - node.jswebmatoView Answer on Stackoverflow
Solution 9 - node.jsDmytro SoltusyukView Answer on Stackoverflow