Home » Scripts, Tutorials

PHP Create Thumbnail Images

Here we are going to observe how to use PHP to generate thumbnails for us. A thumbnail is a smaller size and usually smaller quality of an image shown as preview or link to the original image. Thumbnails can be very useful for faster loading times and quicker display of images on your web pages and a few other reasons. This script will allow us to use a directory on our server and convert all image files in it to a new thumbnail, with dimensions we want, and save it on a new thumbnails directory.

We do this using some PHP functions. First we have to open the directory that we specify as the directory to the images we want to convert to thumbnails. We use the function opendir().

The next part:

while (false !== ($fname = readdir($dir))) {

This loops through the directory until it reaches the end of the files stored in the directory.

Then we make sure it is an image file type by checking its extension:

$valid_extensions = array("jpg","gif","png","jpeg");
if(in_array(strtolower($info['extension']),$valid_extensions)){

We use the function imagecreatefromjpeg() to make an image out of the file with the image extension. With this we grab the image’s width and height to calculate the new height of the thumbnail based off of the $thumbWidth specified in the beginning of the function (200).

We then use the function imagecreatetruecolor() to make a temporary image for the new thumbnail. With it we transfer it to a new image file in our thumbnails directory with the following code:

$genThumb = imagejpeg($tempImage,$pathToThumbs . rand(100,999) .  $fname);

The rand(100,900) make a random 3 digit number in front of the file name. Remove it if you wish.

Here is our function:


function generateThumbs(){
$pathToScreens = "../screenshots/"; // Directory to your images you want converted to thumbnails.
$pathToThumbs = "../screenshots/thumbs/"; // Directory to your thumbnails.
$thumbWidth = 200; // Width of the thumbnails generated.

$dir = opendir($pathToScreens) or die("Could not open directory");
$counter = 0;

while(($fname = readdir($dir)) !== false){
if($fname != "." && $fname != ".."){
// Remove folders.
$valid_extensions = array("jpg","jpeg"); // Only jpeg images allowed.
$info = pathinfo($pathToScreens . $fname);
if(in_array(strtolower($info["extension"]),$valid_extensions)){
// Make sure the file is an image file by checking its extension to the array of image extensions.
$img = imagecreatefromjpeg($pathToScreens . $fname); // Select the file as an image from the directory.
$width = imagesx($img);
$height = imagesy($img);
// Collect its width and height.

$newHeight = floor($height * ($thumbWidth / $width)); // Calculate new height for thumbnail.

$tempImage = imagecreatetruecolor($thumbWidth,$newHeight); // Create a temporary image of the thumbnail.
// Copy and resize old image into new image.
imagecopyresized($tempImage,$img, 0, 0, 0, 0, $thumbWidth,$newHeight,$width,$height);

$genThumb = imagejpeg($tempImage,$pathToThumbs . rand(100,999) . $fname);
// Create the thumbnail with the new width and height in the thumbnails directory.
// I added a rand 3 digit number in front of the file name to avoid overwrite.
$counter++; // Increment.
}
}
}
if($counter > 0){
return $counter . " thumbnails generated from the directory \"".$pathToScreens."\".";
} else {
return "No image files could be processed.";
}
closedir($dir); // Close the directory.
}

?>

Then we can just call it like so:

echo generateThumbs();
1

Popularity: 17% [?]

Share/Bookmark this!

Leave a reply

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

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

This is a Gravatar-enabled weblog. To get your own globally recognized avatar, please register at Gravatar.

Side Notes

This entry was posted by on December 20, 2009 at 9:54 AM and filed under Scripts, Tutorials category.

You can add your comments or trackback from your own site. To keep you updated to the latest discussion, you can subscribe to these comments via RSS.

Recent Entries

Pages

Recent Comments

Resources

Questions & Answers

Just started! Have not answered any questions.

Tag Cloud

background body CSS database date dropdown email error_reporting favicon file filesize form format function global hosting HTML image Javascript limit link linkbar mysql numbers online option ordinalize pagination pattern photoshop PHP resize rows script search snowing stylesheet switch table thumbnail time timestamp upload validate variables

Sponsors