Search code examples
javascriptdata-uri

Image file size from data URI in JavaScript


I am not sure it's even possible but - can I get the image file size from data URI?

For example, let's say there is an IMG element where src goes:

src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...

Based on the src, can I get the image file size by using plain JavaScript? (without server request)


Solution

  • If you want file size, simply decode your base64 string and check the length.

    var src ="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP/// yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
    
    var base64str = src.substr(22);
    var decoded = atob(base64str);
    
    console.log("FileSize: " + decoded.length);