Find out what the width of an image is using jQuery

Go To StackoverFlow.com

1

I have these images that I am getting off my server and a database using PHP

<div class="pics">

<img src="upload/<?php echo $array['image'] ?>" height="200"/>

</div>

There actual sizes are huge, but I need them to all be at a height at 200.

How do I find the width of this image using jQuery, I cant find a tutorial anywhere....

Any help would be appreciated.

Thanks for you're time, J

2012-04-04 20:21
by user979331
Possible duplicate of: http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrom - davidethell 2012-04-04 20:23


0

I would try .innerWidth() instead of .width(), as .width() would include the margin.

$('img').innerWidth();

If your image is really that big, you should consider scaling it down it server-side.

Update

Actually .width() is not adding the margin and furthermore its not even adding the padding. That makes .width() more suitable than .innerWidth(). Thanks SKS.

2012-04-04 20:25
by d_inevitable
width() would include the margin - Not true. .width will return just the elements width without padding/border/margin - Selvakumar Arumugam 2012-04-04 20:38
Hmm, you are right. Sorry I keep confusing the too - d_inevitable 2012-04-04 20:46


7

Try using .width function. something like $('img').width();

More reading.. http://api.jquery.com/width/

Further more, there are .innerWidth and .outerWidth functions to include/exclude padding,border and margins. See below image for details,

enter image description here

2012-04-04 20:23
by Selvakumar Arumugam
Definitely reference what davidethell posted, because .height() and .width() will return 0 if the image has not finished loading when called. Using these methods will work but you need to make sure the image has finished loading - Nick DeFazio 2012-04-04 20:38
@spoonybard896 <img src="upload/<?php echo $array['image'] ?>" height="200"/> doesn't look like he is loading dynamically - Selvakumar Arumugam 2012-04-04 20:40
True, but as I understand it, if the actual image content has not finished loading and you ask for it's width/height, you will get zero in Webkit browsers - Nick DeFazio 2012-04-04 20:47
@spoonybard896 OP never mentioned where he is going to call .width. Even the one in the post will not work if it is not loaded. That post was talking about loading an image using .load and getting the width the image before inserting it in DOM. You CANNOT calculate width of something that is not loaded - Selvakumar Arumugam 2012-04-04 21:08
Just wanted to point out that when using .width and .height, making sure the image has loaded should be taken into accoun - Nick DeFazio 2012-04-05 03:53
Ads