Creating Dynamic Image Thumbnails Using PHP

Creating Dynamic Image Thumbnails Using PHP

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.

Comments

  1. / Reply

    great tutorial on image crop system using php, we could even do it using lots of available php classes.

    • Josh,
    • February 25, 2011
    / Reply

    Great article! Thanks for sharing. I just had to do this for a client.

    • Darek,
    • February 25, 2011
    / Reply

    Thanks for this script. I’m having a problem with it though.

    The script does produce one or two thumbnails correctly and places them in the correct dir, but then it stops and throws this error:

    “HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.”

    Could it be something with my images?

    1. / Reply

      First thing I would check if your trying to create a lot of images is, max execution time. second check to make sure your images are all in the .jpg, .png, or .gif format. If that doesn’t work, shoot me an email threw my portfolio website with the issue and ill do my best to help you out. http://www.ronnicholls.com

    • Josh F,
    • February 25, 2011
    / Reply

    This is awesome! I’ve been looking for a way to dynamically create thumbnails on the fly without resizing manually in Photoshop. Thanks!

    • Ijaas,
    • February 26, 2011
    / Reply

    The smarter choice would be to use http://code.google.com/p/timthumb/ instead of making ur own.

    1. / Reply

      That is actually really nice code to use, I tend to build most of my applications from scratch, so over the years this is just a nice little script that I came up with, And it was more developed for things like, Multiple upload scripts. I some times have to upload 100’s of images at once, and this script mostly came from that.

  2. / Reply

    Its better to use the imagick functions. They need less memory and produce better results.

    1. / Reply

      Correct, imagick is another good alternative :).

  3. / Reply

    I agree with Ijaas – timthumb and phpthumb are alternatives with good support and applications

  4. / Reply

    I agree, imagick is another good alternative

  5. / Reply

    It’s very detailed, thank you very much.

    • gandalf117,
    • September 29, 2011
    / Reply

    thanks a lot, it works!

    Could you just explain how the height or the width gets adjusted?
    Why do you need the third else statement when you cover all the conditions in the first two?

    1. / Reply

      The last if statement is more of a “catch all” just in case by some weird reason it doesn’t fall into the first two if statements.

    • Zahid,
    • January 13, 2012
    / Reply

    Great script, I was looking this to use for my new project and wondering that ever thing is working well

    Thanks

    • Rong,
    • February 13, 2012
    / Reply

    Awesome script and it’s helped me quickly create thumbs but I did have one problem.

    The script throws off an error and creates a black thumbnail if the image is JPG, Jpg, jPG or any variation like that. I corrected this by turning the extension into all lowercase letters by changing:

    switch($stype) {

    to

    switch(strtolower($stype)) {

    • Brandon,
    • April 26, 2012
    / Reply

    I’m trying to figure out how to use this scipt.. I’m a newb. Is this an “in directory” script

    • juvl,
    • July 4, 2012
    / Reply

    Works great, exactly what i was looking for.

    Thanks a lot!

    • Nadeem,
    • April 10, 2013
    / Reply

    very good

    • Ali Haris,
    • April 25, 2013
    / Reply

    Here’s basically the same thing converted into a function:
    https://github.com/aliharis/php-dynamic-thumbnail

    I hope this helps for new comers.

Leave a Reply

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

Deals