Stawa
Stawa

Reputation: 325

How can I display an Image without downloading it from a url in NodeJS?

In NodeJS I used package named node-fetch, also for taking JSON Response, but how about an Image response? How can I do that? In my current codes, It does only save the image not showing like PIL from python.

var tr = "https://i.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI"

export async function get_image() {
    const get_url = await fetch(tr)
    const image = get_url.body.pipe(fs.createWriteStream('./image.png'))
}

await get_image();

Upvotes: 2

Views: 2775

Answers (1)

KyleRifqi
KyleRifqi

Reputation: 509

You can get an image in Base64 format and save it in a variable using the axios module like so:

const axios = require('axios')
const imageURL = 'https://i.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI';

(async ()=>{
    // Get image Buffer from url and convert to Base64
    const image = await axios.get(imageURL, {responseType: 'arraybuffer'});
    const base64Image = Buffer.from(image.data).toString('base64');

    // Do stuff with result...
    console.log(base64Image);
})();

// Or if you prefer, a one liner
(async ()=>{
    const base64Image = Buffer.from((await axios.get(imageURL, {responseType: 'arraybuffer'})).data).toString('base64');
})();

You can check if it worked by using a website to decode the base64 string into an image.

Upvotes: 2

Related Questions