Friday, September 5, 2025
HomeLanguagesJavascriptHow to convert image into base64 string using JavaScript ?

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 :

  • Here we will create a gfg.js file which will include JavaScript code and one gfg.html file.
  • Now we will put onchange on the input type and this will execute a function imageUploaded() when you upload an image.
  • Now we will use a file reader and use the onload event in the file reader than we will get the image URL and we need to remove some text to get the base64 string and store it in a variable named base64String and print on the console.
  • And if you want to use this base64 you can write logic on the button click like here we will alert this base64 String.

Example: This example shows the above-explained approach.

HTML




<!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:

 convert image into base64 string using JavaScript

RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11863 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6701 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS