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.
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>
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);
}
}
Run index.html file in browser you will see and try to browse an image.
Hope this would help you in some case. Have a nice day!
JavascriptFounder 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