Web Design, Development & Marketing

Web Development Articles

PHP: Resize an Image Based on a Maximum Size or Width

This script makes use of the getimagesize() PHP function which returns an array with information on the size of an image. The example PHP script below just uses the width parameter to check an images width and then it is resized if necessary when displayed in the browser.

<?php
$image = "../path/fileName.gif";
if (file_exists($image))
{
  list($width) = getimagesize($image);
  // set the maximum width of the image here
  $maxWidth = 100;
  if ($width > $maxWidth)
  {
    echo "<p><img alt=\"Image\" width=\"$maxWidth\" src=\"$image\" />";
  }
  else
  {
    echo "<p><img alt=\"Image\" src=\"$image\" /></p>\n";
  }
}
else
{
  echo "<p>Image does not exist</p>";
}
?>

This can be a useful script if you want to limit the size of an image which may affect your page layout adversely if too large (i.e. too wide). This is especially useful in cases where you have a large number of images being uploaded to your server, by many different users perhaps, and resizing the original images would be a time consuming task.

Subscribe to RSS Feed Bookmark and Share

Related Links

Related Articles / Posts

Barclaycard ePDQ CPI Integrations (27/05/2009)

HSBC XML API / CPI E-commerce Integrations (02/04/2009)

Recommended Open Source Invoicing System (25/03/2009)

Recent Recommended Links - October 2008 (03/10/2008)

Controlling PHP Register Globals Using .htaccess File (04/03/2008)