How to get HTML5 Canvas.todataurl file size in javascript?
Best way to think about it is that each char represents 6 bits (2^6 == 64, hence the Base64). So times the amount of chars you have by 6 to get the total number of bits. Then divide the total number of bits by 8 to get the amount of bytes, because a byte is 8 bits.
Math.round(base64String.length * 6 / 8);
Which is the same as Math.round(base64String.length * 3 / 4);
.
If you want to know the size of the data-url in bytes you can do:
var imgFileSize = data_url.length;
But that's not the real size of the png size. You can approximate very accurately to the real PNG size this way:
var head = 'data:image/png;base64,';
var imgFileSize = Math.round((data_url.length - head.length)*3/4) ;
Because the Base64 encoding has a 4/3 overhead.
Edit: corrected the size calculation after comments.
I didn't find that Pedro's solution accurate, what i did was to create a blob out of the canvas and then get the fileSize
canvas.toBlob(function(blob){
alert(blob.size);
});
base64 estimates will always vary!
Decode the base64 string and check its length. This method is always 100% accurate!
var content_without_mime = base64.split(",")[1];
var size_in_bytes = window.atob(content_without_mime).length;