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!
JavascriptAs the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him