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
-


Have Questions? Post them here!

Top Hashtags:

Advertisements

Advertisements




Advertisements