Open In App

How to convert image into base64 string using JavaScript ?

In this article, we will convert an image into a base64 string using Javascript. The below approaches show the methods to convert an image into a base64 string using Javascript.

Approach

Example: This example shows the above-explained approach.






<!DOCTYPE html>
<html>
 
<head>
    <title>
        How to convert image into base64 string using JavaScript ?
    </title>
</head>
 
<body>
    <input type="file" name="" id="fileId" onchange="imageUploaded()">
    <br><br>
 
    <button onclick="displayString()">
        Display String
    </button>
    <script>
        let base64String = "";
 
        function imageUploaded() {
            let file = document.querySelector(
                'input[type=file]')['files'][0];
 
            let reader = new FileReader();
            console.log("next");
 
            reader.onload = function () {
                base64String = reader.result.replace("data:", "")
                    .replace(/^.+,/, "");
 
                imageBase64Stringsep = base64String;
 
                // alert(imageBase64Stringsep);
                console.log(base64String);
            }
            reader.readAsDataURL(file);
        }
 
        function displayString() {
            console.log("Base64String about to be printed");
            alert(base64String);
        }
 
    </script>
</body>
</html>

Output:




Article Tags :