Reputation:
I would like to know how to get the size in bytes from the "src" from an "img" tag with HTML/JS.
<img src="https://ofbuckleyandbeatles.files.wordpress.com/2011/01/testpattern.gif"/>
In the above example I would basicly want to know how big "testpattern.gif" is (in bytes).
Thanks in advance.
Upvotes: 17
Views: 32900
Reputation: 91
Sadly the proposed solution does not work since the returned value does not match the image actual size.
Assuming you are using a URL you can do the following:
const fileImg = await fetch(URL_TO_IMG).then(r => r.blob());
This will get the resource through HTTP and then returns the full binary as a blob object, then you can access its properties including its size in bytes as:
fileImg.size
Upvotes: 9
Reputation: 3247
Well, this is 2017 and you can now use Resource Timing API to extract an image's transferSize, encodedBodySize, decodedBodySize within javascript:
Below is the code to access size information for all the imgs on a page (see the caveat to all below):
var imgElems = document.getElementsByTagName('img');
for ( var i=0, len = imgElems.length; i < len; i++ )
{
var url = imgElems[i].src || imgElems[i].href;
if (url && url.length > 0)
{
var iTime = performance.getEntriesByName(url)[0];
console.log(iTime.transferSize); //or encodedBodySize, decodedBodySize
}
}
Upvotes: 22