var data_url=canvas.toDataURL("image/png");
var img=$("#img").attr("src",data_url);
what is the img file size in kb?
Here is the code to do that: var canvas = document. getElementById("ex1"); var dataUrl = canvas. toDataURL(); window.
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 .
Yes, images are loaded asynchronously by the browser.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With