Photo Slideshow – Part One – Batch Resize

September 14th, 2007 @

The idea is simple, I want to be able to upload a directory full of pictures and have a slideshow. I have a few groups of photos to share with the world and more and more I’m keen on the idea of coding it myself rather then use a service like flickr or Picasa.

The first step was to upload my photos. I created a directory ‘images’ and inside that directory I created ‘originals’ and ‘700w’. I then uploaded all my pictures to the originals directory.

I then created a script to automatically resize all the images in my directory.

<?php
//it can take a bit to resize a bunch of images..
//php will by default only run for 30 seconds
//this removes that limitation
set_time_limit(0);

//open our directory
if ($handle = opendir('images/originals')) {
    //go through our directory filenames one by one
    while (false !== ($file = readdir($handle))) {
        //ignore our . and .. directories
        if ($file != "." && $file != "..") {
            //open our image
            $image = imagecreatefromjpeg('images/originals/'."$file");
            if ($image === false) { closedir($handle); die ('Unable to open image'); }

            //get our original image dimensions
            $owidth = imagesx($image);
            $oheight = imagesy($image);

            //our new dimensions, hardcoded for a 700 width
            //second line adjusts the height to keep the same aspect ratio
            $nwidth = 700;
            $nheight =  $newheight=($oheight/$owidth)*$nwidth;

            //create a new blank image the right size
            $tmpimg=imagecreatetruecolor($nwidth,$nheight);
            //and resize/resample our original into it
            imagecopyresampled($tmpimg,$image,0,0,0,0,$nwidth,$nheight,$owidth,$oheight);

            //write to file
            $filename = "images/700w/". $file;
            imagejpeg($tmpimg,$filename);

            //clean up
            imagedestroy($image);
            imagedestroy($tmpimg);
        }
    }
    closedir($handle);
}
?>

I saved this as ‘resize.php’ and ran it with ‘php resize.php’. After about a minute my 700w directory was full of resized images, and I’m all set up for the slideshow I want.

Leave a Reply