Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding Height and Width Attributes

Status
Not open for further replies.

CliffLandin

Programmer
Nov 14, 2004
81
US
Is there a way to find out the height and width attributes of an image? I have a gallery page that displays images from a database. I want the user to be able to enter pictures of any size (within reason) and display them at maximum size if bigger or the correct size if smaller than the max size. Does that make sense? So I want to be able to get the height and width attributes from the image and then say

<img src='whatever' width=$width height=$height />

where $width is either = max. size or actual size.
ditto for $height.

When in doubt, go flat out!

 
Assuming you want to do this client-side (you haven't said otherwise), there are several ways you can achieve this:

1. Let all the images load as HTML elements in the source, with no width/height specified. Then, onload, go through detecting widths and heights, and shrinking accordingly.

2. Load no images in the HTML, but when the page has loaded, load them all into JS objects. Then, detect their widths and heights, and add them at the correct size into the DOM.

The advantage of option 1 is that people without JS enabled will still see the images (albeit at full size). The disadvantage is that if they are really big images, they will be displayed at their natural size (notwithstanding automatic resizing by the browser).

If you want to do this server-side, assuming you want to do this in JS (why else would you ask in a JS forum), then option 2 would work just fine, allowing you to output the regular HTML with no problems.

To define an image object in JS (whether client-side or server-side), you would use:

Code:
var tempImg = new Image();
tempImg.src = 'some/path/and/fileName.jpg';

You can then get the width and height of the image using:

Code:
var imgWidth = img.width;
var imgHeight = img.height;

If you need a formula for resizing one dimension while keeping the aspect ratio the same, just shout. It's simple maths, so you may already have worked it out.

Hope this helps,
Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top