Submit Tips/Quickies

PHP Functions : GD

Resizing images on the fly

Submitted By: Joe Sircy
Date: 10/26/00 22:34

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.



Comments:
php5 compatibilityCiprian M.08/25/07 16:56
Image resizing in HTMLChaitanya Jakhadi12/03/04 04:05
Disregard prior messageConnie Goss08/03/02 01:51
can drawtext with Chineseleon12/01/00 11:27
RE: ImprovementsJoe Sircy11/09/00 02:04
ImprovementsDidimo Grimaldo11/01/00 22:43
RE: GD???Mario Mekinda10/31/00 17:49
Error on http://www.phpbuilder.com/tips/item.Mario Mekinda10/31/00 17:37
GD???Joe Sircy10/27/00 01:21
 

If you are looking for help, please post on the appropriate forum here. Your questions will be answered much more quickly.

Add A Comment:

Name:

Email:

Subject:

Message:

To reduce spam posts, messages are now manually approved

You are not [logged in]. That means your account will not get credit for this post.