Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryWeb Page and Site Features

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Make Smaller Copy of Image

Along my decades of programming, I sometimes needed software to shrink an image to a smaller size. This week, I required one again.

As usual, what I required was specialized. Moreover, as usual, I was able to reuse much of what I had previously done. This time, the code to reuse was extracted from software I built about 2½ years ago and have been using ever since.

Then I had a thought. (Yes, me, having a thought.) So long as I was extracting and reusing code, I should build something for you, too.

The function is named MakeSmallerCopyOfImage. The function can be included within your PHP software.

You give the function the location of a PNG, GIF, or JPEG image. The function will copy the image, resize it, and save it in the same directory as the original. The copy will be smaller with the same width/height proportion as the original.

Here is the source code of the function. It is ready to use. Information about the function and how to use it follows.

function MakeSmallerCopyOfImage($arr)
{
   /* Version 1.0, October 8, 2025, Will Bontrager Software LLC */
   // Data error check.
   foreach( $arr as $k => $v ) { $arr[$k] = trim($v); }
   $err = array();
   if( (!isset($arr['width'])) or $arr['width']<1 ) { $err[] = 'Missing or incorrect width specification.'; }
   if( (!isset($arr['height'])) or $arr['width']<1 ) { $err[] = 'Missing or incorrect height specification.'; }
   if( (!isset($arr['namemod'])) or strlen($arr['width'])<1 ) { $err[] = 'Missing or incorrect namemod specification.'; }
   if( (!isset($arr['source'])) or (!file_exists($arr['source'])) ) { $err[] = 'Missing or incorrect source image specification.'; }
   if( count($err) ) { return implode("\n<br>",$err); }
   // Create operation variables.
   // -- Determine destination file location.
   $ta = explode('/',$arr['source']);
   $sourceFname = array_pop($ta);
   $sourceFnoExt = implode('/',$ta);
   $ta = explode('.',$sourceFname);
   $Fext = strtolower(array_pop($ta));
   $sourceFnoExt .= '/' . implode('.',$ta);
   if( ! preg_match('!^_!',$arr['namemod']) ) { $arr['namemod'] = '_'.$arr['namemod']; }
   $dest = "$sourceFnoExt{$arr['namemod']}.$Fext";
   if( file_exists($dest) )
   {
      $ta = explode('/',$dest);
      $destFname = array_pop($ta);
      return "New image file name $destFname already exists.";
   }
   // -- Determine size and type for smaller image.
   $src = $arr['source'];
   $destWidth = $arr['width'];
   $destHeight = $arr['height'];
   $th = getimagesize($src);
   $srcWidth = $th[0];
   $srcHeight = $th[1];
   $ta = explode('/',$th['mime']);
   if( count($ta)>1 ) { $type = array_pop($ta); }
   else { $type = $Fext; }
   $type = strtolower($type);
   $th = array();
   $ta = array();
   $adjustment = min( ( $destWidth / $srcWidth ), ( $destHeight / $srcHeight ) );
   $destWidth = number_format( $srcWidth * $adjustment );
   $destHeight = number_format( $srcHeight * $adjustment );
   if( $srcWidth <= $destWidth and $srcHeight <= $destHeight )
   {
      return 'No resizing necessary. Original image is already equal to or smaller than resize dimensions.';
   }
   // Start new image.
   $newimg = imagecreatetruecolor($destWidth, $destHeight);
   switch($type)
   {
       case 'jpeg': 
       case 'jpg' : $oldimg = imagecreatefromjpeg($src); break;
       case 'png' : $oldimg = imagecreatefrompng($src);  break;
       case 'gif' : $oldimg = imagecreatefromgif($src);  break;
       default    : return "Error: Unsupported image type.";
   }
   // Handle any transparency in GIF or PNG.
   if($type == "gif" or $type == "png")
   {
       imagecolortransparent( $newimg, imagecolorallocatealpha($newimg, 0, 0, 0, 127) );
       imagealphablending( $newimg, false );
       imagesavealpha( $newimg, true );
   }
   // Create image.
   imagecopyresampled($newimg, $oldimg, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
   $outtype = $type;
   switch($outtype)
   {
       case 'jpeg':
       case 'jpg' : imagejpeg( $newimg, $dest, 100 ); break;
       case 'png' : imagepng( $newimg, $dest, 9 );  break;
       case 'gif' : imagegif( $newimg, $dest );  break;
   }
   return 'OK';
} # function MakeSmallerCopyOfImage()

When the function is called, it expects an array of information. The array has four items:

  1. Where the target image is located.

    $myarray['source'] = $_SERVER['DOCUMENT_ROOT'].'/images/IMG_1681.jpg';
    

    The image location needs to be the exact server location.

    If you are uncertain about the server location, first determine the image URL (load the image into your browser and copy the URL in the browser's address bar). Then replace the protocol and domain name with $_SERVER['DOCUMENT_ROOT']. Here is an example before and after:

    https://example.com/images/IMG_1681.jpg
    $_SERVER['DOCUMENT_ROOT'].'/images/IMG_1681.jpg'
    
  2. How the file name for the copy shall be determined (a modified version of the original image file name):
    $myarray['namemod']='_resized';
    

    The smaller copy of the image must have a different file name than the original because both will be stored in the same directory.

    For the value of $myarray['namemod'], specify a few characters to append to the file name. You might specify, as examples, _resized or _thumnail. Using one of the examples, the image myimage.jpg would then be resized with the myimage_resized.jpg or myimage_thumnail.jpg file name.

  3. The maximum pixel width of the resized image.

    $myarray['width']=300;
    

    The resized image will be no wider than the number of pixels specified with this array item.

    Images are resized with dimensions proportional to the original image dimensions. Thus, the resized width might be less than specified if the height is at maximimum.

  4. The maximum pixel height of the resized image.

    $myarray['height']=300;
    

    The resized image will be no higher than the number of pixels specified with this array item.

    Images are resized with dimensions proportional to the original image dimensions. Thus, the resized height might be less than specified if the width is at maximum.

To clarify why it is possible that the resized image might not be the exact size specified with $myarray['width'] and $myarray['height'], here is an explanation:

When the dimensions are specified, they are "no larger than" dimensions.

The resized image dimensions will be proportional to the original image. Thus, the resulting width and height might not both be exactly as specified. For example, if you specify 300 for the resized width and 300 for the height, and if the original image is 3333 wide and 2222 high, then the resized image will be 300 wide and 200 high.

In other words, the resized image will be as large as it can be and still fit snugly within the dimensions you specify.

The MakeSmallerCopyOfImage function will not copy and resize images with dimensions larger than the current image. If the original image is already the specified size, or is smaller than the specified size, nothing is done — except for a "No resizing necessary" message.

The function will not overwrite a file to save the resized image. Instead, it will assume the resizing has already occurred.

Here is a ready-to-go PHP script to demonstrate how the MakeSmallerCopyOfImage is used.

<?php

// Customize the values of the $myarray array.
$myarray['source']=$_SERVER['DOCUMENT_ROOT'].'/images/IMG_1681.jpg'; // Exact file location.
$myarray['namemod']='_resized';   // Text for renaming copied file.
$myarray['width']=300;            // Number of pixels.
$myarray['height']=300;           // Number of pixels.

// Run the function.
$response = MakeSmallerCopyOfImage($myarray);
// The response will either be "OK" or an operational message.
echo $response;


function MakeSmallerCopyOfImage($arr)
{
   /* Version 1.0, October 8, 2025, Will Bontrager Software LLC */
   // Data error check.
   foreach( $arr as $k => $v ) { $arr[$k] = trim($v); }
   $err = array();
   if( (!isset($arr['width'])) or $arr['width']<1 ) { $err[] = 'Missing or incorrect width specification.'; }
   if( (!isset($arr['height'])) or $arr['width']<1 ) { $err[] = 'Missing or incorrect height specification.'; }
   if( (!isset($arr['namemod'])) or strlen($arr['width'])<1 ) { $err[] = 'Missing or incorrect namemod specification.'; }
   if( (!isset($arr['source'])) or (!file_exists($arr['source'])) ) { $err[] = 'Missing or incorrect source image specification.'; }
   if( count($err) ) { return implode("\n<br>",$err); }
   // Create operation variables.
   // -- Determine destination file location.
   $ta = explode('/',$arr['source']);
   $sourceFname = array_pop($ta);
   $sourceFnoExt = implode('/',$ta);
   $ta = explode('.',$sourceFname);
   $Fext = strtolower(array_pop($ta));
   $sourceFnoExt .= '/' . implode('.',$ta);
   if( ! preg_match('!^_!',$arr['namemod']) ) { $arr['namemod'] = '_'.$arr['namemod']; }
   $dest = "$sourceFnoExt{$arr['namemod']}.$Fext";
   if( file_exists($dest) )
   {
      $ta = explode('/',$dest);
      $destFname = array_pop($ta);
      return "New image file name $destFname already exists.";
   }
   // -- Determine size and type for smaller image.
   $src = $arr['source'];
   $destWidth = $arr['width'];
   $destHeight = $arr['height'];
   $th = getimagesize($src);
   $srcWidth = $th[0];
   $srcHeight = $th[1];
   $ta = explode('/',$th['mime']);
   if( count($ta)>1 ) { $type = array_pop($ta); }
   else { $type = $Fext; }
   $type = strtolower($type);
   $th = array();
   $ta = array();
   $adjustment = min( ( $destWidth / $srcWidth ), ( $destHeight / $srcHeight ) );
   $destWidth = number_format( $srcWidth * $adjustment );
   $destHeight = number_format( $srcHeight * $adjustment );
   if( $srcWidth <= $destWidth and $srcHeight <= $destHeight )
   {
      return 'No resizing necessary. Original image is already equal to or smaller than resize dimensions.';
   }
   // Start new image.
   $newimg = imagecreatetruecolor($destWidth, $destHeight);
   switch($type)
   {
       case 'jpeg': 
       case 'jpg' : $oldimg = imagecreatefromjpeg($src); break;
       case 'png' : $oldimg = imagecreatefrompng($src);  break;
       case 'gif' : $oldimg = imagecreatefromgif($src);  break;
       default    : return "Error: Unsupported image type.";
   }
   // Handle any transparency in GIF or PNG.
   if($type == "gif" or $type == "png")
   {
       imagecolortransparent( $newimg, imagecolorallocatealpha($newimg, 0, 0, 0, 127) );
       imagealphablending( $newimg, false );
       imagesavealpha( $newimg, true );
   }
   // Create image.
   imagecopyresampled($newimg, $oldimg, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight);
   $outtype = $type;
   switch($outtype)
   {
       case 'jpeg':
       case 'jpg' : imagejpeg( $newimg, $dest, 100 ); break;
       case 'png' : imagepng( $newimg, $dest, 9 );  break;
       case 'gif' : imagegif( $newimg, $dest );  break;
   }
   return 'OK';
} # function MakeSmallerCopyOfImage()

?>

Tell it where to find your original image and save it on your server. Load it into your browser and observe its magic.

The MakeSmallerCopyOfImage function can be placed into your PHP scripts. It is designed to make a copy of an image and reduce its size.

(This content first appeared in Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2025 Will Bontrager Software LLC