Convert Image to Base 64 String and Display using Pure Javascript

Sovary July 7, 2022 420
1 minute read

Convert Image to Base 64 String using Pure Javascript; Hi today I will show very short demo example how to convert image which is browse from local machine to base64 image string with Javascript and display in image element.

thumbnial_php_javascript_convert_image_to_base64_string_display

Design Simple HTML Form

First I will show how HTML Form should behave. I am going to insert a file input element to browse and drop an image file to browser. The drop file will trigger a method to perform javascript encode to base64 string.

Create file index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Image to Base64 - CamboTutorial.com</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
      <h1 class="title">Image to Base64 - CamboTutorial.com</h1>
      <input type="file" onchange="imageUploaded(this)">
      <br>
      <br>
      <img src="" id="image" width="200px"/>
      <br>
      <br>
      <textarea id="display" rows="20" cols="55"></textarea>
  </body>
  <script src="script.js"></script>
</html>

Implementation Javascript

In HTML form we have place onchange() event to trigger whenever browse change file from local machine. After change or browse to different image file we will show all base64 string into textarea.

Create file script.js in the same directory

function imageUploaded(element) 
{
  let file = element.files[0];
  if(file === undefined) return;
  console.log(file);
  let reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onloadend = function() 
  {
    // Display base64 in textbox
    let output = document.querySelector("#display");
    output.value = "";
    output.value = reader.result;
    let image = document.querySelector("#image");
    image.setAttribute('src',reader.result);
  }
}

Result Output

Run index.html file in browser you will see and try to browse an image.

javascript image to base64 string display

Hope this would help you in some case. Have a nice day!

Javascript 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him