JavaScript Convert Image/File into Base64 String

avatar
Published: Dec 05, 2022

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>
<html>
<head>
	<title>File size validation using Javascript - shouts.dev</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
	<script src="https://code.jquery.com/jquery-3.4.1.js"></script>  
</head>
<body>
<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()">
				</div>
			</form>

			<div>
				<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="">
			</div>
		</div>
	</div>
</div>

<script>
  	function imageConverter() {
        var image = event.target.files[0];
       
       	var reader = new FileReader();
 
      	reader.onloadend = function() {
 
        	$("#code").attr("href",reader.result);
        	$("#code_text").removeClass('d-none');
        	$("#image_text").removeClass('d-none');
 
        	$("#code").text(reader.result);
 
        	$("#img").attr("src", reader.result);
      }
      reader.readAsDataURL(image);
    }
</script>
</body>
</html>

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. 🙂

Comments

No comments yet…