Get Base64 string of an image in JavaScript

The Base64 format of an image is the encoded string of that image with proper printable characters only. Loading base64 image on the web page can speed up load time. It can also help to skip the external image file loading process.

In this article, you will see how to get the base64 format of an image from HTML file type input using JavaScript. First of all, let’s create our file type input field where we will select our image. Below is our field:

<input type="file" onchange="encodeBase64(this)" />

In our HTML input tag, you can notice that we have pass onchange event listener. Inside this event listener, we have passed our function.

Now we have to create our JavaScript function encodeBase64(). Below is our JavaScript function:

function encodeBase64(elm) {
  var file = elm.files[0];
  var imgReader = new FileReader();
  imgReader.onloadend = function() {
    console.log('Base64 Format', imgReader.result);

Now when we select an image file from our HTML input, it will show the base64 format of our image in our console log. This is because, when the input value change, it calls our function. Inside our function, we are showing the image base64 code in the console.

Also, read:


You can try it and run the code on your browser. Also, it will work not only for images but also you can get base64 string of any other types of file.

I hope you have understood how to get the base64 formatted string of an image from the file input type HTML tag in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *