Search the Site

Sponsors

bottom corner

Get image width and height with PHP

With the getimagesize() function in PHP, I was able get width, height, and other properties of images to help me lay out a web page.

This page is filed under keyword(s): php.

I was working on my World War II photo gallery recently. The gallery's HTML code, particularly the main content section, looks something like the following.


<div id="content">
	<div class="main_column">
		<img src="images/helloWorld.jpg">
		<!--
		The photograph and other "main content" goes here.
		The width of this column is 600px.
		-->
	</div>

	<div class="extra_column">
		<!--
		This is the vertical side bar.
		If the width of the photo in the main section is more
		than 600px, it will overlap this div.
		-->
	</div>
</div>

Because my vertical navigation bar is on the right side of the page, if a photograph is larger than a particular width, it overlaps the vertical bar. I decided to remove the vertical bar if the photo is too large; let us assume that if the image width is larger than 580 pixels, it is too large. To apply the logic, I used the getimagesize() function. A quick example on this function is below.

list($imageWidth, $imageHeight, $imageType, $imageAttr) = getimagesize($imgName);
echo("The width of the image is ".$imageWidth." pixels.");
// Sample output: "The width of the image is 600 pixels."

I used the following PHP code to make my page work the way I want to based on width of the image.


<div id="content">
	<?php
	$imgName = "helloWorld.jpg";

	list($imageWidth, $imageHeight, $imageType, $imageAttr) = getimagesize($imgName);

	if ($imageWidth <= 580) { ?>
		<div class="main_column">
	<?php } ?>

	<img src="images/helloWorld.jpg">
	<!--
	The photograph and other "main content" goes here.
	-->

	<? if ($imageWidth <= 580) { ?>
		</div>
		<div class="extra_column">
		<!--
		This is the vertical side bar.
		Only show this if image width
		is 580 pixels or smaller.
		-->
		</div>
	<?php } ?>
</div>

Beyond width, the getimagesize() function in PHP also outputs other properties; the output is an array containing four elements. As you may have noticed, in my above example, I captured the following properties.

  • 0 $imageWidth : Width of the image in pixels; integer.
  • 1 $imageHeight : Height of the image in pixels; integer.
  • 2 $imageType : Type of the image; integer. Possible values are as follows:
    ValueDescription
    GIF
    JPG
    PNG
    SWF
    PSD
    BMP
    TIFF (Intel)
    TIFF (Motorola)
    JPC
    10 JP2
    11 JPX
    12 JB2
    13 SWC
    14 IFF
    15 WBMP
    16 XBM
  • 3 $imageAttr : HTML-formatted attributes; string. Example: 'height="600" width="400"'

Did you find this page useful? Please consider browsing other articles or subscribing to the RSS feed to keep up with latest.

This page is filed under keyword(s): php.
Author: C. Peter Chen
Last updated: 17 Nov 2008

bottom corner