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,

Example:
<!html>
    <head>
        <title>Image to Base64 String Example: Code2care.org</title>
    </head>
<body>

<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;
 
</script>
</body>
</html>
Image to Base64 String JavaScript

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap