Creating Dynamic Image Thumbnails Using PHP

by in Development on 25th Feb 2011 · Comments

Think how many websites that are built and need an image, and a thumbnail version of that image. When building boxofficeBUZ I came across a very simple but normal issue. Why waste time creating an image and thumbnail version in Photoshop or any other image processing software, why not do it dynamically with php.

Creating Dynamic Image Thumbnails Using PHP
Image credit: dcreeves2000


From there I started researching php's built in GD image library, and ways to create thumbnails. There is a lot of information on creating thumbnails, most either create a thumbnail by just giving a height or width. If you can specify a height and width the thumbnails usually result in being stretched. It is from here that I started to combine scripts and eventually came up with a standard thumbnail script that I use for most of my websites. This not only creates a thumbnail, but crops the image keeping its dimensions intact and results in not stretching the thumbnail image.

The Code!

In this tutorial, we will be using php to create on the fly dynamic thumbnails of images. This tutorial will show you how to do it for all major image formats ie. png, jpg, gif.

Step 1 is telling the script what size & width you would like the thumbnail images to be.

$nw = 150;    //New Width
$nh = 100;    //new Height

Now we want to tell the script the source file, and the destination of the thumbnail.

$source = "images/test/test.jpg";    //Source file
$dest = "images/test/thumb/test.jpg";    //Destination *Note you can add or change the name of the file here. ie. thumb_test.jpg

The next part of the code will dynamically figure out the extension of the file. We use php's explode function to find the period before the file extension, and then use count to find everything after the period, resulting in the file extension.

$stype = explode(".", $source);
$stype = $stype[count($stype)-1];

The next step is to get the original image size.

$size = getimagesize($source);
$w = $size[0];    //Images width
$h = $size[1];    //Images height

The next part of the code is switch statement to make sure we use the right php function to create the thumbnail image.

switch($stype) {
    case 'gif':
    $simg = imagecreatefromgif($source);
    break;
    case 'jpg':
    $simg = imagecreatefromjpeg($source);
    break;
    case 'png':
    $simg = imagecreatefrompng($source);
    break;
}

The next part of the code is what does all the magic, it will create the thumbnail, and move it into the desired folder. The last line of the next block of code goes in this order (destination image, destination, quality of image).

$dimg = imagecreatetruecolor($nw, $nh);
$wm = $w/$nw;
$hm = $h/$nh;
$h_height = $nh/2;
$w_height = $nw/2;

if($w> $h) {
    $adjusted_width = $w / $hm;
    $half_width = $adjusted_width / 2;
    $int_width = $half_width - $w_height;
    imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} elseif(($w <$h) || ($w == $h)) {     $adjusted_height = $h / $wm;     $half_height = $adjusted_height / 2;     $int_height = $half_height - $h_height;         imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h); } else {     imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h); }     imagejpeg($dimg,$dest,100); 

Now the code all together.

 $source = "images/test/test.jpg";    //Source file $dest = "images/test/thumb/test.jpg";    //Destination *Note you can add or change the name of the file here. ie. thumb_test.jpg $size = getimagesize($source); $w = $size[0];    //Images width $h = $size[1];    //Images height switch($stype) {     case 'gif':     $simg = imagecreatefromgif($source);     break;     case 'jpg':     $simg = imagecreatefromjpeg($source);     break;     case 'png':     $simg = imagecreatefrompng($source);     break; } $dimg = imagecreatetruecolor($nw, $nh); $wm = $w/$nw; $hm = $h/$nh; $h_height = $nh/2; $w_height = $nw/2;     if($w> $h) {
    $adjusted_width = $w / $hm;
    $half_width = $adjusted_width / 2;
    $int_width = $half_width - $w_height;
    imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
} elseif(($w <$h) || ($w == $h)) {
    $adjusted_height = $h / $wm;
    $half_height = $adjusted_height / 2;
    $int_height = $half_height - $h_height;

    imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
} else {
    imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}

imagejpeg($dimg,$dest,100);

Varaition of code

This is just an added bonus variation of the code, it will take a desired folder, find every image in that folder, and create thumbnails of all the images on the fly.

$thumb_directory =  "images/thumb";    //Thumbnail folder
$orig_directory = "images/full";    //Full image folder

/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = @opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1){ //Check to make sure the folder opened

$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;

while ($file = @readdir($dir_handle))
{
    /* Skipping the system files: */
    if($file=='.' || $file == '..') continue;

    $file_parts = explode('.',$file);    //This gets the file name of the images
    $ext = strtolower(array_pop($file_parts));

    /* Using the file name (withouth the extension) as a image title: */
    $title = implode('.',$file_parts);
    $title = htmlspecialchars($title);

    /* If the file extension is allowed: */
    if(in_array($ext,$allowed_types))
    {

        /* If you would like to inpute images into a database, do your mysql query here */

        /* The code past here is the code at the start of the tutorial */
        /* Outputting each image: */

        $nw = 150;
        $nh = 100;
        $source = "images/full/{$file}";
        $stype = explode(".", $source);
        $stype = $stype[count($stype)-1];
        $dest = "images/thumb/{$file}";

        $size = getimagesize($source);
        $w = $size[0];
        $h = $size[1];

        switch($stype) {
            case 'gif':
                $simg = imagecreatefromgif($source);
                break;
            case 'jpg':
                $simg = imagecreatefromjpeg($source);
                break;
            case 'png':
                $simg = imagecreatefrompng($source);
                break;
        }

        $dimg = imagecreatetruecolor($nw, $nh);
        $wm = $w/$nw;
        $hm = $h/$nh;
        $h_height = $nh/2;
        $w_height = $nw/2;

        if($w> $h) {
            $adjusted_width = $w / $hm;
            $half_width = $adjusted_width / 2;
            $int_width = $half_width - $w_height;
            imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
        } elseif(($w <$h) || ($w == $h)) {
            $adjusted_height = $h / $wm;
            $half_height = $adjusted_height / 2;
            $int_height = $half_height - $h_height;

            imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
        } else {
            imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
        }
            imagejpeg($dimg,$dest,100);
        }
}

/* Closing the directory */
@closedir($dir_handle);

}

Conclusion

Why waste your time cutting and cropping images with image processing software, when you can just use a PHP built in function to create image thumbnails on the fly. It will give you more free time in the end, and once mastered there are many more things you can do with PHP's image functions.

Ronald Nicholls is a freelance web developer, and Owner/CEO of Geek Suite, Inc. A graduate of Multimedia Design at durham college. While at Durham he spent his last 2 years of school freelancing, and learning more about the industry. In July 2010 He started Geek Suite Inc. a network of websites that cover a variety of topics and interests, with the basic theme being, "Nerd / Geek" culture.