Is there a reliable, framework independent way of determining the physical dimensions of a <img src='xyz.jpg'>
resized on the client side?
views:
194answers:
2
+1
A:
You can preload the image into a javascript Image object, then check the width and height properties on that object.
Myles
2009-12-22 05:16:28
Of course - I don't have to put it into the document. Will do it that way, cheers!
Pekka
2009-12-22 05:23:27
+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
2009-12-22 05:18:42
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
2009-12-22 09:45:23
@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
2010-01-02 18:19:39