Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 436
venkat7668 Avatar asked Sep 01 '13 10:09

venkat7668


People also ask

How do I get canvas toDataURL?

Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.

What is toDataURL JavaScript?

toDataURL() method returns a data URL containing a representation of the image in the format specified by the type parameter. The desired file format and image quality may be specified. If the file format is not specified, or if the given format is not supported, then the data will be exported as image/png .

Is canvas toDataURL async?

Yes, images are loaded asynchronously by the browser.

How do I get an image URL from Canva?

To get the image data URL of the canvas, we can use the toDataURL() method of the canvas object which converts the canvas drawing into a 64 bit encoded PNG URL. If you'd like for the image data URL to be in the jpeg format, you can pass image/jpeg as the first argument in the toDataURL() method.


2 Answers

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.

like image 124
Pedro L. Avatar answered Sep 25 '22 01:09

Pedro L.


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;
like image 21
Kareem Avatar answered Sep 27 '22 01:09

Kareem