DEV Community

Cover image for How to Convert Images to Base64 Data URLs in JavaScript
Dom (dcode)
Dom (dcode)

Posted on

How to Convert Images to Base64 Data URLs in JavaScript

It's easy to convert JPG and PNG images to Base64 data URLs with JavaScript. Let me show you how.

In case you didn't know, a data URL is simply a long string of characters that represent the binary of your image. You can then use this URL in your HTML <img> tags.

Very convenient.

Video Tutorial

If you prefer a video tutorial, you can watch this 4 minute video on my YouTube channel:

Step 1. File Input

You'll need a file input field in your HTML. Just like this:

<input type="file" id="fileInput" />
Enter fullscreen mode Exit fullscreen mode

You can name the ID whatever you like.

Step 2. Change Event

In JavaScript, you'll need to attach a change listener to react to when the user chooses a file.

const fileInput = document.getElementById("fileInput");

fileInput.addEventListener("change", e => {
    console.log(e);
});
Enter fullscreen mode Exit fullscreen mode

If you choose a file and check the console, you'll notice the event object. Take note of the target.files property.

Step 3. File Reader Setup

Next, you'll need to get a reference to the selected file and create a new instance of FileReader. This file reader object can read files in different forms.

fileInput.addEventListener("change", e => {
    const file = fileInput.files[0];
    const reader = new FileReader();
});
Enter fullscreen mode Exit fullscreen mode

Replace the console.log line with the above code.

Step 4. Read as Data URL

Now that we have the FileReader created, we can tell it to read the file as a Base64 Data URL.

reader.addEventListener("load", () => {
    // Base64 Data URL πŸ‘‡
    console.log(reader.result);
});

reader.readAsDataURL(file);
Enter fullscreen mode Exit fullscreen mode

As you can see we attach the load event to the FileReader. Once the file has finished being read, we can grab the Data URL by accessing reader.result.

Full Code

const fileInput = document.getElementById("fileInput");

fileInput.addEventListener("change", e => {
    const file = fileInput.files[0];
    const reader = new FileReader();

    reader.addEventListener("load", () => {
        // Base64 Data URL πŸ‘‡
        console.log(reader.result);
    });

    reader.readAsDataURL(file);
});
Enter fullscreen mode Exit fullscreen mode

Done! Feel free to use this Data URL in your <img> tags. Just don't make the images too large 😎

Enrol Now πŸ‘‰ JavaScript DOM Crash Course

If you're learning web development, you can find a complete course on the JavaScript DOM at the link below πŸ‘‡
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Course Thumbnail

Top comments (1)

Collapse
 
ruslanastratov profile image
Ruslan Astratov

Thanks!