This code converts the image file to Base64 string data. But I want to reduce the size of the base64 string because the size of the base64 string data I converted is larger than the image file. Is that possible?
<input id="inputFileToLoad" type="file" accept="image/*" onchange="encodeImageFileAsURL();"/>
<div id="imgTest"></div>
<script type='text/javascript'>
function encodeImageFileAsURL(){
var filesSelected = document.getElementById("inputFileToLoad").files;
var fileSize = filesSelected[0].size;
if(fileSize < 10000000){
if (filesSelected.length > 0){
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent){
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
} else {
alert("File exceeded");
}
}
</script>
64 is 2^6(6 bits). This means that every char(8 bits) contains only 6 bits of information. So in order to convey the same amount of information base64 requires 33.3% more bits compared to binary.
The only thing you can do is reduce the size of the original image before you apply base64, this will reduce the size of the base64 string by the same ratio.