Finding the height and width of an image in ASP

When an image is displayed in an <img> tag it can be helpful to the browser if the width and height attributes are used to specify the dimensions of the image. Without this information the page will resize as the images load. Fortunately the image dimensions are often stored at the start of a file and csImageFile is able to read this information without fully loading or decompressing an image.

To find image dimensions with csImageFile call the GetDimensions method and this will populate the properties ReadHeight and ReadWidth. GetDimensions will raise an exception if the file cannot be opened, but it will simply return zero dimensions if the file is not a valid image. This makes it useful for running through an entire folder of files which may not all be readable supported images.

Here is an example of using GetDimensions:

Set Image = Server.CreateObject("csImageFile.Manage")
Image.GetDimensions "C:\images\test.jpg"
Response.Write Image.ReadWidth & "<br/>"
Response.Write Image.ReadHeight & "<br/>"

This is quite easy to use with static image files because the dimensions can be found and then written into the IMG tag. When there are multiple images, use a single instance of csImageFile. When GetDimensions is called, it resets the values of ReadHeight and ReadWidth.

With dynamically generated image a different approach is needed. If an image is being generated dynamically and its size is unknown, some calculation will be needed to find the new size. For example, if it is a thumbnail image that is resized to 10% of its original size, GetDimensions could be used on the original and the resulting dimensions divided by 10.

Example:

Set Image = Server.CreateObject("csImageFile.Manage")
Image.GetDimensions "C:\images\test.jpg"
Response.Write Round(Image.ReadWidth / 10) & "<br/>"
Response.Write Round(Image.ReadHeight / 10) & "<br/>"

We have deliberately picked a simple example. It would be much more complicated with a resized image that might be either landscape or portrait and it might not have been changed if it was below a certain size. It is questionable whether it is worth the effort to find the image dimensions, especially as the width and height attributes are not required, even for strict XHTML validation.