How to Convert the Image into a Base64 String Using JavaScript
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 toDataURL() to get the Base64 representation. In fact, it is a data URL, but it contains the Base64-encoded image:
This can only be useful if you don’t need the original Base64 string or original image 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 blob via XMLHttpRequest and 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:
<!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.