How to Convert Images to Data URLs Using JavaScript (Base64)

Robin
Updated on November 7, 2022

You can easily convert images to base64 data URLs using JavaScript. Any type of image (jpg, png) can be used in this process. It will transform an image into a string.

Call FileReader() constructor to create a new instance. To convert an image to a data URL, use the readAsDataURL() method from the FileReader instance and pass the image to it. When the reading completes, access the data string from the result property.

It is a very useful way to store an image in localStorage with JavaScript because as you know, localStorage only allows string data type.

There are many other uses for data URLs. We will discuss those in this article as well. So that you can understand its importance.

Now let's see how can we use JavaScript to transform an image into a piece of string.

Convert Images to Data URLs With JavaScript

There are 3 simple steps to convert an image to a Data URL with javascript:

  1. Extract the image file from the HTML <input> element.
  2. Get a FileReader instance from FileReader() constructor.
  3. Read the image file as a data URL using readAsDataURL() method.

It doesn't matter which type of image file you are using, you will use these 3 steps for the conversion process.

Step 1: Get Image File From Input Element

You need to have an <input> element with type="file" in your HTML. By defining this type, we are telling the browser to accept a file as the input value.

          <input type="file" id="select-image">
        

To extract the image from this element in JavaScript, use the change event. Whenever the input value changes this event will fire and we can get the file from event.target.files[0] property.

          const fileInput = document.getElementById('select-image');

// Lister to the change event on the <input> element
fileInput.addEventListener('change', (event) => {
    // Get the selected image file
    const imageFile = event.target.files[0];

});
        

A user can choose any type of file with this input. You can perform a file type validation in JavaScript to make sure that users are selecting only images, not any other file type.

Here, the imageFile variable will contain the selected image.

Step 2: Setup FileReader() Constructor Function

We need to create a new instance of the FileReader() constructor. This instance has many properties and methods to read files in different forms.

          fileInput.addEventListener('change', (event) => {
    // Get the selected image file
    const imageFile = event.target.files[0];

    if (imageFile) {
        const reader = new FileReader();

    }
});
        

Now I will use the reader object to convert the image file to a data URL. You can also use it to read the file as a text, buffer, array of buffers, etc.

You can learn more about the FileReader() constructor here.

Step 3: Read The Image File As Data URL

Our FileReader instance has a readAsDataURL() method to read an image file. Call this method and pass the file that you have extracted from the <input> element.

When this method completes the reading, it will emit a load event. That's why I am using addEventListener() method to listen to the load event.

          // Convert the image file to a string
reader.readAsDataURL(imageFile);

// FileReader will emit the load event when the data URL is ready
// Access the string using result property inside the callback function
reader.addEventListener('load', () => {
    // Get the data URL string
    console.log(reader.result);
});
        

Inside the event callback function, we can get our data URL from reader.result property. This property will return a string that contains the image data.

          const fileInput = document.getElementById('select-image');

// Lister to the change event on the <input> element
fileInput.addEventListener('change', (event) => {
    // Get the selected image file
    const imageFile = event.target.files[0];

    if (imageFile) {
        const reader = new FileReader();

        // Convert the image file to a string
        reader.readAsDataURL(imageFile);

        // FileReader will emit the load event when the data URL is ready
        // Access the string using result property inside the callback function
        reader.addEventListener('load', () => {
            // Get the data URL string
            console.log(reader.result);
        });
    }
});

        

You will get a different result from this property if you use a different method to read the image file. These are the methods we can use to read a file:

  • readAsArrayBuffer() – It reads the file as an array of buffers.
  • readAsBinaryString() – It reads the file as raw binary data.
  • readAsDataURL() - It reads a file as a base64 encoded string.
  • readAsText() – It reads a file as a text string.

After converting an image file to a data URL, one question you might ask is – what can you do with it?

What Can You Do With The Data URL String?

When you get the data URL string from your image, you can use that string in different ways. You can store an image in the localStorage as a string with this method.

If you need to display it on the page, you will get that string from the localStorage and show it using an HTML <img> element.

          reader.addEventListener('load', () => {
    const img = document.createElement('img');

    // Set data URL as the src attribute value
    img.setAttribute('src', reader.result);

    document.body.appendChild(img);
});
        

It is also possible to preview images using JavaScript before uploading them to the server. When the data URL is ready, create an <img> element and set the data URL as the src attribute value.

In this way, we can display the uploaded images on the page so that users can see which images they are uploading. It gives an amazing user experience.

Also Read: Best Ways to Create Dynamic HTML Element & CSS in JavaScript

Conclusion

In many situations, you may not have access to a URL that you can use to display an image on your web page. We can use the data URL in those moments.

There are many other applications of this method. You have seen some of them. That's why I have tried to explain the conversion process in a few steps.

Now you can follow those steps and convert an image to a base64 data URL in JavaScript.

Related Posts