PHP Generate the Thumbnails for use in an Image Gallery

A fastest way to convert the image into a smaller size then save it is to use the PHP function, exif_thumbnail. However, to generate thumbnails, you can use the script below. It’s more of a utility script though but it’s simple to moderate it for use.
<?PHP
set_time_limit(0); //use this to make sure the script doesn't time out on large number of images.
//error_reporting(E_NONE); //use this to disable errors in a production script

function getmicrotime() {
    $temparray=split(" ",microtime());
    $returntime=$temparray[0]+$temparray[1];
    return $returntime;
}

//lets make it slightly proper HTML. not valid, but can be changed quickly to be
echo "<html>
<head><title>Processing...</title></head>
<body>"
;

$maindir = "." ; //change this to what ever directory needs scanning
$mydir = opendir($maindir) ;
$starttime=getmicrotime();
$i = 0; //set the count of images processed to 0
while($fn = readdir($mydir)) //scan through the whole directory
    {//open while

        $startimagetime = getmicrotime();
        $ext = strtolower(substr($fn,strlen($fn)-3)); //get the extension of an image
        if ($ext == "jpg") {
            $i++; //increase the number of images processed
            echo $fn ." is being processed....<br>";
            flush(); //needed to display each image progress
           

            $image = exif_thumbnail($fn, $width, $height, $type);

            if ($image!==false) {
                    //if there is a good enough thumbnail to use, we have it here.
                    //extract it and put it in the file, call it [original image name].thumb.jpg
                 $handle = fopen ($fn.".thumb.jpg", 'a');
                 //write the thumbnail image
                 fwrite($handle, $image);
            } else {
                 // no thumbnail available, handle the error here
                 echo "No thumbnail available for file ".$fn."<br>";
            }
        }
}
closedir($mydir);
$endtime=getmicrotime();

echo "<br>All Images have been processed, script is finshed.<br>Total processing time: ";
print $endtime-$starttime;
echo "<br> Images processed: " .$i;
echo "</body>";
echo "</html>"

?>

All PHP Scripts on this website are provided by phpscripts4u.com where you can find all the latest PHP code snippets, plugins and libraries.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>