I am using the javascript file API to read images using the readAsDataURL method and found that my images were always larger than their originals, in one case even 1MB larger.
This is the code I am using
$(function() {
'use strict';
$('#source').on('change', function(evt) {
var reader = new FileReader();
var file = evt.target.files[0];
var reader = new FileReader();
reader.onloadend = function() {
$('#encoded').text('El tamaño codificado es ' + reader.result.length / 1024 + ' kb')
}
if (file) {
$('#original').text('El tamaño original es ' + file.size / 1024 + ' kb')
reader.readAsDataURL(file);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="source" type="file">
<div id="original"></div>
<div id="encoded"></div>
I don't know if I am missing something here or if there is some reason for this behavior. Does anyone know what could be the cause?
Base64 is a printable character representation of binary content. To be printable, Base64 uses an alphabet of 64 characters, 6 bits per character.
The "waste" appears because Base64 is stored/transported in bytes (like everything else), so for each byte you store in Base64 representation you need 1 byte + 2 bits of the next storage byte.. disk, network, memory, etc.
A diagram says more than a thousand words:
In other words, each 3-byte block of the original file is converted into 4 bytes in Base64 format, so that at least the size will increase by a ratio of 4/3, that is, 133%. To this you must add the padding (the file sizes will not always be multiples of 3) and the carriage returns found in the transfer file.
I just tried with an image of the following sizes:
Using your example, I get:
Let's go to the San English Wikipedia https://en.wikipedia.org/wiki/Base64
And in the San Wikipedia in Spanish https://es.wikipedia.org/wiki/Base64
Whether it is 137% or 140%, the size will increase when using Base64. Cheers!
FileReader transforms the image to a base64 text string:
Whereas your variable
file
is an object of typeFile
that contains the image in binary .For more information about the object
File
you can read this documentation