views:

194

answers:

2

Is there a reliable, framework independent way of determining the physical dimensions of a <img src='xyz.jpg'> resized on the client side?

+1  A: 

You can preload the image into a javascript Image object, then check the width and height properties on that object.

Myles
Of course - I don't have to put it into the document. Will do it that way, cheers!
Pekka
+4  A: 

You have 2 options:

Option 1:

Remove the width and height attributes and read offsetWidth and offsetHeight

Option 2:

Create a JavaScript image object, set the src, and read the width and height (you don't even have to add it to the page to do this).

function getImgSize(imgSrc) {
    var newImg = new Image();

    newImg.onload = function() {
    var height = newImg.height;
    var width = newImg.width;
    alert ('The image size is '+width+'*'+height);
    }

    newImg.src = imgSrc; // this must be done AFTER setting onload

}

Edit by Pekka: As agreed in the comments, I changed the function to run on the ´onload´ event of the image. Otherwise, with big images, height and width would not return anything because the image was not loaded yet.

Gabriel McAdams
Excellent, that's the way I'm going to do it. Thanks!
Pekka
That won't work with images that aren't loaded yet. It might be worth adjusting it to work properly for other people stumbling across this answer.
J-P
@Gabriel, I am using this but with an `newImg.onload` function to make sure the image is loaded when I set the width/height. Are you ok with me editing your answer accordingly?
Pekka
Thats not a problem
Gabriel McAdams