Menu Close

How to Get an Image from the Web and Encode it into a Base64 String with Node.js and JavaScript?

convert-image-into-code
In this article, we’ll look at how to get an image from the web and encode it into a base64 string with Node.js and JavaScript.

To get an image from the web and encode it into a base64 string with Node.js, we can use the Axios HTTP client to get the image and save it in a buffer object.

Then we can convert the saved buffer object into a base64 string.

To install Axios, we run:

npm i axios 

Then we write:

const axios = require('axios')

const getImage = async () => {
    const image = await axios.get('https://picsum.photos/200/300', {
        responseType: 'arraybuffer'
    });
    const returnedB64 = Buffer.from(image.data).toString('base64');
    console.log(returnedB64)
}
getImage() 

to import the axios package.

And then we create the getImage function that calls axios.get to make a GET request to get the image.

The 2nd argument sets the responseType to 'arraybuffer' so the image will be assigned to an array buffer with the image.

Next, we call Buffer.from with image.data to convert the array buffer object to a buffer.

Then we call toString with 'base64' to convert the buffer object to a base64 string and assign that to the returnedB64 variable.

Posted in NodeJs, NPM

You can also read...