CancelImage Upload

How to resize all the images contained within a folder at once with PHP

Let's face it: only the biggest Photo enthusiasts on the planet will want to spend endless amounts of time resizing hundreds of images one at a time. Your average individual or web designer neither has the will or the passion for that kind of display of commitment.

Luckily however, as programmers, we can develop our own short cuts in life. Well, on computers at least. If only there was a code to prevent us from having to wait at bus stops and cues at shopping centres. Anyway, here then is a tutorial on how to develop a multi image resize function.

Really the following code consists of two parts. The first task is to load each file contained within the specified folder, so that we can send them one by one to our image resize function. Here is how this task is accomplished:


$source = "originals";

$directory = opendir($source);

//Scan through the folder one file at a time

while(($file = readdir($directory)) != false)

       echo "<br>".$file;

       //Run each file through the image resize function

       imageResize($file, $source.'/', 900, 700);



As you can see the above function is simple enough. With the function readdir() we load every file contained within the folder "Originals". Upon this we send each file one by one to the function imageResize(), our Max Height and Width demands being 900 x 700 Pixels. Here is the function imageResize():


function imageResize($file, $path, $height, $width)

       $target = 'new/';

       $handle = opendir($path);

       if($file != "." && $file != ".." && !is_dir($path.$file))

              $thumb = $path.$file;

              $imageDetails = getimagesize($thumb);

              $originalWidth = $imageDetails[0];

              $originalHeight = $imageDetails[1];

              if($originalWidth > $originalHeight)

                     $thumbHeight = $height;

                     $thumbWidth = ($originalWidth/($originalHeight/$thumbHeight));


                     $thumbWidth = $width;

                     $thumbHeight = ($originalHeight/($originalWidth/$thumbWidth));


              $originalImage = ImageCreateFromJPEG($thumb);

              $thumbImage = ImageCreateTrueColor($thumbWidth, $thumbHeight);

              ImageCopyResized($thumbImage, $originalImage, 0, 0, 0, 0, $thumbWidth,
              $thumbHeight, $originalWidth, $originalHeight);

              $filename = $file;

              imagejpeg($thumbImage, $target.$filename, 100);





Add both these functions up, and there's your multi image resize. Piece of cake!

Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •