0

I have an <img> tag which is filled with dynamic src attribute. I would like to display the image size (in bytes) upon image load using javascript/jQuery.

I tried using the below. But, it returns zero in all 3 properties.

$('#img').on('load',
                function() {
                    var imgUrl = $(this).attr("src");
                    var imgPerf = performance.getEntriesByName(imgUrl)[0];
                    console.log(Math.round(imgPerf.decodedBodySize)); // returns 0
                    console.log(Math.round(imgPerf.encodedBodySize)); // returns 0
                    console.log(Math.round(imgPerf.transferSize)); // returns 0
                });

Is there any other possible ways to get the image size value?

FYI, the images are loaded from different domain.

1
  • The problem with "image size" is that it will depend on the compression, so the file size and the image size are not always the same thing. Commented Feb 4, 2022 at 13:34

1 Answer 1

1

if you have image url you can try this:

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
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use this to only load the image once (rather than use src= to have the browser load it then re-load it to get the size) - see : stackoverflow.com/a/44069294/2181514

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.