JavaScript Convert Image/File into Base64 String

Hi devs, today I'll show you how to convert an image into base64 string. Sometimes we need to convert our images into base64 string. After completing today's tutorial you'll never face any problems to converting into base64 string. So, let's see how we can easily convert images into base64 string.

Convert Image/File into base64 String

For converting our image into base64 string we will use onloadend event of FileReader() class. onloadend event execute when a file load successfully. For mor info see the below doc about onloadend. Now let's see the below source code.

<!DOCTYPE html>
	<title>File size validation using Javascript -</title>
	<link rel="stylesheet" href="[email protected]/dist/css/bootstrap.min.css">
	<script src=""></script>  
<div class="container">
	<div class="row justify-content-center mt-5">
		<div class="col-md-8">
			<form enctype="multipart-formdata">
				<div class="form-group">
					<label for="image">Image</label>
					<input type="file" class="form-control" name="file" id="image" onchange="imageConverter()">

				<p id="code_text" class="d-none">Uploaded Image bas64 Code</p>
				<p style="height: 400px;overflow: auto;padding: 20px;" href="javascript:void(0)" id="code" contenteditable="true"></p>
				<p id="image_text" class="d-none">Uploaded Image After Converting into bas64</p>
				<img id="img" src="">

  	function imageConverter() {
        var image =[0];
       	var reader = new FileReader();
      	reader.onloadend = function() {
        	$("#img").attr("src", reader.result);

Which will produce the below output.

Convert Image to base64 String

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐Ÿ™‚