javascripthtml5-canvas

How to get HTML5 Canvas.todataurl file size in javascript?


var data_url=canvas.toDataURL("image/png");

var img=$("#img").attr("src",data_url);

what is the img file size in kb?


Solution

  • 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.