#native_company# #native_desc#
#native_cta#

Resizing images on the fly

By Joe Sircy
on October 26, 2000

This is a nifty function to resize an image of unknown height and width to a pre-determined size. This is very useful if you have user submitted images, like the ones here on php builder.


<? function setImageSize($image_file) {

   $maxSize = 100; // set this varible to max width or height

   $image_size = getimagesize($image_file,&$image_info);
   $width = $image_size[0];
   $height = $image_size[1];

   if($width > $maxSize || $height > $maxSize) {

      if($width > $maxSize) {
        $z = $width;
        $i = 0;
        while($z > $maxSize) {
          --$z; ++$i;
        }
        $imgSizeArray[0] = $z;
        $imgSizeArray[1] = $height - ($height * ($i / $width));

      } else {

        $z = $height;
        $i = 0;
        while($z > $maxSize) {
          --$z; ++$i;
        }
        $imgSizeArray[0] = $width - ($width * ($i / $height));
        $imgSizeArray[1] = $z;
      }

  } else {

     $imgSizeArray[0] = $width;
     $imgSizeArray[1] = $height;
  }

  return $imgSizeArray;
} ?>

The function returns an array with the new width and height of the image.
Here is an example of using the function:


<? $imgSize = setImageSize("sample.jpg"); ?>

<img src="sample.jpg" width="<? echo $imgSize[0];?>" height="<? echo $imgSize[1]">

This will resize the image to either 100 by x or x by 100 pixels, but only if it is larger than 100.