Convert image from url into data uri in node.js

827 Views Asked by At

I have been looking for a JavaScript solution to converting an image from an external url to a data uri. I have installed multiple packages and tested multiple methods but have not been able to find a usable method for doing so.

What I want:

var url = 'https://static-00.iconduck.com/assets.00/npm-icon-512x512-qtfdrf37.png';
var output = convertToUri(`${url}`); // doesn't need to be a one liner just anything relatively simple that works
res.send(`${output}`);

The closest thing I have: (using data-uri package from npm)

var url = 'https://static-00.iconduck.com/assets.00/npm-icon-512x512-qtfdrf37.png';
data_uri.encode(=`${url}`, function(results){
    console.log(results); // this comes in json form that doesn't seem to want to cooperate with JSON.parse();
                          // if somebody could figure this out that would be equally as helpful
                          // https://www.npmjs.com/package/data-uri
});
2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER

I have found a way to do this using image-to-base64 package:

const imgtoBase64 = require('image-to-base64')

app.get('/', (req, res) => {
    const URL = 'https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';

    imgtoBase64(`${URL}`)
            .then( (response) => {
                console.log('data:image/png;base64,' + response);  // the response will be the string base64.
            }
        )
        .catch(
            (error) => {
                console.log(error);
            }
        )
});
0
Maxime Baker On

You can use this code to convert urls to base64 :

const fetch = require('node-fetch')
    , base64stream = require('base64-stream');

const URL = 'https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';

fetch(URL)
    .then((res) => {
        return new Promise((resolve, reject) => {
            let chunks = [];
            let myStream = res.body.pipe(base64stream.encode());
            myStream.on('data', (chunk) => {
                chunks = chunks.concat(chunk);
            });
            myStream.on('end', () => {
                resolve(chunks.toString('base64'));
            });
        });
    })
    .then(console.log);

Source : https://gist.github.com/muety/3ef97aad64ac733831e41ef5025133e0