Software, your way.
How To Get Good Custom Software
(Download)
(PDF)
burger menu icon
WillMaster

WillMaster > LibraryWeb Content Preparation

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!

Image Resizing

The accompanying PHP image resizing software is designed to quickly resize all images in a directory.

When an image is resized, it is saved in a new file. The resizing software leaves the original image as it was found.

The dimensions of the image are proportionally reduced to fit within your specified maximum width and maximum height measures. If the original image dimensions already fit within the maximums, no resizing is done.

The first version of this software was made 3 years ago for another project. A few things were updated to make this new version easier to use. And it has been named "Bulk Image Resize".

Bulk Image Resize is likely to be used mostly to create thumbnail images for web page menus or to accompany image descriptions for clicking to the larger image or to a related article. There are other uses. Resizing images larger than thumbnails for embedding within articles, for example.

When an image is resized, the new image is saved with a file name like the original but with characters appended. As an example, an image resized from myimage.png may be saved as myimage_resized.png.

The characters for appending to resized image file names (_resized in the above example) are specified by you. As with maximum width and height, the file name characters may optionally be specified with the script URL.

Customizing and Uploading the Script

The Bulk Image Resize PHP script is further below. It may be uploaded to your server as is or the defaults may be customized first.

Now, or when done customizing, upload the Bulk Image Resize script into a directory that will be only for resizing images. Name the script imagesResize.php or other *.php file name. The examples in this article assume imagesResize.php is the file name.

As noted, customizing the defaults is optional. The current defaults are:

  • Maximum width: 200
  • Maximum height: 200
  • File renaming characters: _resized

Each of those is addressed below the software source code.

<?php
/*
Bulk Image Resize
(Resize all images in a Directory)
Version 1.1
July 25, 2022
Version 1.0, August 28, 2019
Will Bontrager Software LLC
https://www.willmaster.com/
*/

/* Optional customization */
$Resize['max-width'] = 200; // Default number of pixels if not specified with software URL (max-width=123)
$Resize['max-height'] = 200; // Default number of pixels if not specified with software URL (max-height=123)
$Resize['namechars'] = '_resized'; // Default characters if not specified with software URL (namechars=xyz)
/* End of customization */

if( isset($_GET['max-width']) ) { $Resize['max-width'] = $_GET['max-width']; }
if( isset($_GET['max-height']) ) { $Resize['max-height'] = $_GET['max-height']; }
if( isset($_GET['namechars']) ) { $Resize['namechars'] = $_GET['namechars']; }
$Resize['files'] = array();
foreach(glob('*.jpeg') as $f) { $Resize['files'][] = $f; }
foreach(glob('*.jpg') as $f) { $Resize['files'][] = $f; }
foreach(glob('*.png') as $f) { $Resize['files'][] = $f; }
foreach(glob('*.gif') as $f) { $Resize['files'][] = $f; }
ResizeImagesWithinArray($Resize);
echo 'OK';
exit;

function ResizeImagesWithinArray($data)
{
   global $G, $Resize;
   $arr = array();
   $arr['width'] = $data['max-width'];
   $arr['height'] = $data['max-height'];
   $count = count($data['files']);
   for( $i=0; $i<$count; $i++ ) //$data['files'] as $f );
   {
      $filename=__DIR__.'/' . $data['files'][$i];
      $ext = imprintGetFileNameExtension($filename);
      $fname = preg_replace('/\.[^\.]+$/','',$filename);
      $arr['filename'] = $filename;
      $arr['ext'] = $ext;
      $arr['fname'] = $fname;
      $arr['source'] = "$fname.$ext";
      $arr['dest'] = "$fname{$Resize['namechars']}.$ext";
      ResizeTheImage($arr);
   }
} # function ResizeImagesWithinArray()

function ResizeTheImage($arr)
{
   $src = trim($arr['source']);
   $dest = $arr['dest'];
   $destWidth = $arr['width'];
   $destHeight = $arr['height'];
   $arr = array();
   $th = getimagesize($src);
   $srcWidth = $th[0];
   $srcHeight = $th[1];
   $ta = explode('/',$th['mime']);
   if( count($ta)>1 ) { $type = array_pop($ta); }
   else { $type = imprintGetFileNameExtension($src); }
   $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; }
   // 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 true;
} # function ResizeTheImage()


function imprintGetFileNameExtension($p)
{
   $ta = explode('.',$p);
   $ext = array_pop($ta);
   return $ext;
} # function imprintGetFileNameExtension()
?>

Optional customizations —

The defaults in the Bulk Image Resize source code may be customized. (See Using Bulk Image Resize further below for information about overriding the defaults.)

The maximum width default in the above source code is 200 (pixels): $Resize['max-width'] = 200;

The default width may be changed by changing the 200 value.

The maximum height default in the above source code is 200 (pixels): $Resize['max-height'] = 200;

The default height may be changed by changing the 200 value.

The default characters to append to resized image file names is _resized: $Resize['namechars'] = '_resized';

The default characters may be changed by changing the _resized value.

Those are the optional customizations, default values that the script will use when necessary. Bulk Image Resize can now be uploaded into the directory that will be only for resizing images.

Using Bulk Image Resize

When imagesResize.php has been uploaded and there is at least one image file in that same directory, the script can be run.

Make a note of the URL of imagesResize.php and type its URL into your browser's address bar. Example:

https://example.com/resizedir/imagesResize.php

When run, imagesResize.php automatically resizes all *.png, *.jpg, *.jpeg, and *.gif images files in the directory that are larger than the maximum dimensions. Each resized file is saved as the original file name with specific characters appended.

To override the defaults specified in the Bulk Image Resize software source code, use URL parameters. Each of the defaults can be overriden.

Here is an example of the imagesResize.php script URL with parameters.

https://example.com/resizedir/imagesResize.php?max-width=100&max-height=150&namechars=(100x150)

The max-width=100 parameter overrides the default with a maximum width of 100 pixels. Change 100 to the maximum width you prefer.

The max-height=150 parameter overrides the default with a maximum height of 150 pixels. Change 150 to your preference.

The namechars=(100x150) parameter overrides the default with (100x150) to be appended to the file name when saving the resized image. Change (100x150) as appropriate for your implementation.

One or more of the above three may be specified in the imagesResize.php URL parameter for resizing images.

Once the script is in the directory with images to resize, the work is very fast. Run the Bulk Image Resize with or without parameters appended to its URL and the software resizes all the images that have a height or width larger than the specified maximum.

(This article 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-2024 Will Bontrager Software LLC