views:

24984

answers:

9

Is there any javascript or jquery apis or methods to get the dimensions of an image on the page?

+24  A: 

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
Rex M
+16  A: 

Using JQuery you do this:

var imgWidth = $("#imgIDWhatever").width();
Ian Suttle
+4  A: 

Also (in addition to Rex and Ian's answers) there is imageElement.naturalHeight and imageElement.naturalWidth which provide the heigh and width of the image itself (rather than the image element).

olliej
These are FF only.
Jourkey
+5  A: 

The thing all other have forgot is that you cant check image size before it loads. When the author checks all of posted methods it will work probably only on localhost. Since jQuery could be used here, remember that 'ready' event is fired before images are loaded. $('#xxx').width() and .height() should be fired in onload event or later.

Thinker
A: 

you can also use

var image=document.getElementById("imageID"); var width=image.offsetWidth; var height=image.offsetHeight;

praveenjayapal
+13  A: 

You can programmatically get the image and check the dimensions using Javascript...

var img = new Image();
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
alert(img.width + 'x' + img.height);

This can be useful if the image is not a part of the markup.

Josh Stodola
+3  A: 

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';
Lee Hesselden
A: 

JQuery Answer:

$height = $('#image_id').attr('height');
$width  = $('#image_id').attr('width');
Eli Geske
A: 

ok guys, i think i improved the source code to be able to let the image load before trying to find out its properties, otherwise it will display '0 * 0', because the next statement would have been called before the file was loaded into the browser. Requires jquery...

function getImgSize(imgSrc){

var newImg = new Image();

newImg.src = imgSrc;

var height = newImg.height;

var width = newImg.width;

p = $(newImg).ready(function(){

return {width: newImg.width, height: newImg.height};

});

alert (p[0]['width']+" "+p[0]['height']);

}

claudio