Converting Images and Image URLs to Base64 in Node.js

Introduction

Base64 encoding allows binary data to be represented in a format that looks and acts as if it were plain text. One common use-case of Base64 encoding is to convert images into Base64 format, which can be directly embedded in HTML or CSS files. This is done to more easily transfer or store image data without having to deal with binary data, which many protocols and file formats can't handle properly.

In this Byte, we'll see how to convert images and image URLs to Base64 in Node.js.

Link: For more general overview of converting/decoding Base64 strings with Node.js, see our article Encoding and Decoding Base64 Strings in Node.js.

Image to Base64 Conversion in Node.js

To convert an image to Base64 in Node.js, we'll need the fs module, which is a built-in module for file I/O operations. Here is an example:

const fs = require('fs');

fs.readFile('image.png', (err, data) => {
    if (err) throw err;
    let base64Image = Buffer.from(data, 'binary').toString('base64');
    console.log(base64Image);
});

In the above code, we're reading the image file using fs.readFile() and then converting the binary data to Base64 using Buffer.from().toString('base64').

Note: Our example assumes the image is in the same directory as your script, so be sure to adjust the path accordingly if it is not.

Asynchronous Image to Base64 Conversion

The above code works fine, but it's synchronous, which means it will block the Node.js event loop. To make it asynchronous, we can use the readFile method in a different way:

const fs = require('fs').promises;

async function convertImageToBase64() {
    const data = await fs.readFile('image.png');
    let base64Image = Buffer.from(data, 'binary').toString('base64');
    console.log(base64Image);
}

convertImageToBase64();

In this code, we're using the fs.promises.readFile() method, which returns a promise that resolves with the content of the file.

Asynchronous Conversion with Callbacks

If you prefer to use callbacks instead of promises, you can use the fs.readFile() method like this:

const fs = require('fs');

fs.readFile('image.png', (err, data) => {
    if (err) throw err;
    let base64Image = Buffer.from(data, 'binary').toString('base64');
    console.log(base64Image);
});

This version of fs.readFile() takes a callback function that will be called once the file is read. The callback receives two arguments: an error object (if any) and the data from the file.

Image URL to Base64 Conversion in Node.js

Before we jump into the code, why would we want to do this in the first place?

Encoding images as Base64 and embedding them directly into an HTML <img> tag can have many benefits, particularly the following:

  • Reducing HTTP Requests and therefore improve load times.
  • Better portability and support. HTML with images embedded like this work in more contexts, like emails.
  • Better content security by avoiding cross-origin requests or serving content over secure connections.

Although it's worth noting that there are some drawbacks, like increasing the size of the HTML document, which may offset some of the performance gains.

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

In Node.js, converting an image URL to Base64 can be achieved using the request module along with the built-in Buffer class. This Base64 data can then be embedded directly into an HTML image tag, allowing the image to be displayed within the web page without linking to an external file.

First, you'll need to install the request module using npm:

$ npm install request

Here's an example of how to convert an image URL to Base64 and embed it in an HTML <img> tag:

const request = require('request');

request.get('http://example.com/image.jpg', { encoding: null }, (error, response, body) => {
    if (!error && response.statusCode == 200) {
        let base64Image = `data:${response.headers['content-type']};base64,` + Buffer.from(body).toString('base64');
        console.log('<img src="' + base64Image + '"/>');
    }
});

The encoding: null option ensures that the response body is returned as a buffer. We then prefix the Base64 data with the appropriate MIME type to create a data URL, which can be used directly in an <img> tag.

Using Axios for Image URL to Base64 Conversion

Another popular library for making HTTP requests in Node.js is Axios. You can use Axios to convert an image URL to Base64 and then embed it in an HTML <img> tag.

To use Axios, you'll first need to install it via npm:

$ npm install axios

Here's how you can use Axios to convert an image URL to Base64 and embed it in an HTML <img> tag:

const axios = require('axios');

axios
    .get('http://example.com/image.jpg', { responseType: 'arraybuffer' })
    .then(response => {
        let base64Image = `data:${response.headers['content-type']};base64,` + Buffer.from(response.data).toString('base64');
        console.log('<img src="' + base64Image + '"/>');
    })
    .catch(error => console.log(error));

Again, we're setting the responseType option to 'arraybuffer' and prefixing the Base64 data with the appropriate MIME type, resulting in a data URL that can be embedded directly in an <img> tag.

Note: Don't forget to handle errors in your promises! You can use a .catch() block to catch and handle any errors that might occur during the HTTP request or the conversion process.

Conclusion

Converting images and image URLs to Base64 in Node.js is a relatively straightforward process thanks to the built-in Buffer class and libraries like request and axios.

You can choose to use callbacks or promises, depending on your specific use-case and personal preference. Regardless of the method you choose, these techniques provide a simple way to work with image data in your Node.js apps.

Last Updated: August 19th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms