JavaScript: Convert an Image into Base64 String

There are multiple ways in which you can convert an image into its Base64 String, one of those ways is using Canvas,

        <title>Image to Base64 String Example:</title>

<h2>Image Displayed using IMG Tag:</h2>
<img src="code2care-logo.jpg" id="myImg" alt="myImg"/>    

<h2>Image Displayed using Base64 String Tag:</h2>
<div id="myImg64" alt="myImg64"></div>

<script type='text/javascript'>

    var image = document.getElementById('myImg');
    var canvas = document.createElement('canvas');  
    canvas.getContext('2d').drawImage(image, 0, 0, image.naturalHeight, image.naturalWidth);
    var base64ImageString = canvas.toDataURL();
    document.getElementById("myImg64").innerHTML = base64ImageString;
Image to Base64 String JavaScript

Have Questions? Post them here!
Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.