How can I convert an image into Base64 string using JavaScript?

15-Jun-2023

.

Admin

How can I convert an image into Base64 string using JavaScript?

This tutorial shows you convert image to base64 string jquery. I explained simply about how to convert image to base64 string jquery. this example will help you how can i convert an image into base64 string using javascript. you will learn javascript - image convert to base64. Alright, let’s dive into the steps.

You can use the FileReader API to read the image file and convert it into a Base64 string. Here is an example code snippet:

Example 1:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>How can I convert an image into Base64 string using JavaScript? - NiceSnippets.Com</title>

</head>

<body>

</body>

<script type="text/javascript">

// select the image file input element

const input = document.querySelector('input[type="file"]');

// add event listener for when a file is selected

input.addEventListener('change', () => {

// create a new FileReader object

const reader = new FileReader();

// read the selected file as a data URL

reader.readAsDataURL(input.files[0]);

// define callback function for when reading is complete

reader.onload = () => {

// get the Base64 string from the data URL

const base64String = reader.result.split(',')[1];

console.log(base64String);

// do something with the Base64 string, like send it to a server or display it in an img element

};

});

</script>

</html>

In this example, we first select the input element that allows users to select an image file. We then add an event listener for when a file is selected. When this happens, we create a new FileReader object and use its `readAsDataURL` method to read the selected file as a data URL. Once reading is complete, we extract the Base64 string from the data URL by splitting it at the comma separator and taking the second part (which contains just the Base64 string). Finally, we log this string to the console (for demonstration purposes) and do something with it, such as sending it to a server or displaying it in an img element.

#JavaScript