How to Convert the Image into a Base64 String Using JavaScript
Read this tutorial and learn several methods of converting an image to a Base64 string using JavaScript. Choose the right approach for you and try examples.
There are several approaches in JavaScript that can help you with converting the image into a Base64 string.
Canvas
Firstly, create a canvas, then load the image into it and use <kbd class="highlighted">toDataURL()</kbd> to get the Base64 representation. In fact, it is a data URL, but it contains the Base64-encoded image:
Note: The image server must allow CORS (Cross-Origin Resource Sharing). Otherwise, the canvas will be tainted, and toDataURL() will throw a security error.
Javascript create canvas convert the image into a Base64
Note that this method may alter the original image format or compression, so it may not be suitable if you need to preserve the exact original file type. Be aware that this method may return different results for the same image depending on the browser and operating system. It will return not only different Base64 values but also different images.
FileReader
Firstly, load the image as a blob using the modern fetch API, then use the FileReader API to convert it to a dataURL:
Javascript use the FileReader API to convert it to a dataURL
This approach has better compression and works for other file types as well.
Images from the local file system
If you need to convert images from the user’s file system, you should use the FileReader API:
Javascript use the FileReader API convert images from the user’s file system
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<input type="file" onchange="encodeImageFileAsURL(this)" />
<script>
function encodeImageFileAsURL(element) {
let file = element.files[0];
let reader = new FileReader();
reader.onloadend = function() {
document.write('RESULT: ', reader.result);
}
reader.readAsDataURL(file);
}
</script>
</body>
</html>The FileReader object allows web apps to read the contents of files stored on the user's computer asynchronously, using File or Blob objects to specify the file or data to read.
Note: To extract a raw Base64 string without the data:image/...;base64, prefix, use reader.result.split(',')[1]. Always implement proper error handling (e.g., try...catch or .catch()) for production applications.