No, it’s not yet another PHP thumbnail generation tutorial! I recently needed a function to:

  • create square thumbnails
  • don’t crop the initial image, but scale it and fill with white background
  • center the thumbnail in the square
  • call the function in a loop to process an entire folder

I found no suitable example and I decided that instead of digging too much it’s better to create my own function and a class for it.

Let’s start with a photo that we need to create a thumbnail for:

Nice kid, huh?

Nice kid, huh?


… and what we want to achieve:
danut_thumb


First step would be the thumbnail generation snippet:

$square_size = 167;
$quality = 100;
//get original image attributes
list($width, $height, $type, $attr) = getimagesize($photos_dir."/".$file);
$thumb=imagecreatefromjpeg($photos_dir."/".$file);
$thumb_p = imagecreatetruecolor($square_size, $square_size);
imagecopyresampled($thumb_p, $thumb, 0, 0, 0, 0, $square_size, $square_size, $width, $height);
//save the file
imagejpeg($thumb_p,$thumbs_dir."/".$file,$quality);

This would be the result:
danut1
As we can see, the photo is distorted and we need to scale it, by adding 2 variables:

//set dimensions
if($width> $height) {
        $width_t=$square_size;
        //respect the ratio
        $height_t=round($height/$width*$square_size);
} elseif($height> $width) {
        $height_t=$square_size;
        $width_t=round($width/$height*$square_size);
}
else {
        $width_t=$height_t=$square_size;
}

We also need to change the imagecopyresampled function call to add these 2 new variables:

imagecopyresampled($thumb_p, $thumb, 0, 0, 0, 0, $width_t, $height_t, $width, $height);

The new result would be:
danut2
The image is not distorted anymore but now it’s not centered. We need to move the point where the scaled image appears on the thumb to the right with a number of pixels equal to the half of the difference between height and width of the thumb. This offset is implemented also in the imagecopyresampled function, the first 2 zeros from the set of 4.

//set dimensions
if($width> $height) {
        $width_t=$square_size;
        //respect the ratio
        $height_t=round($height/$width*$square_size);
        //set the offset
        $off_y=ceil(($width_t$height_t)/2);
        $off_x=0;
} elseif($height> $width) {
        $height_t=$square_size;
        $width_t=round($width/$height*$square_size);
        $off_x=ceil(($height_t$width_t)/2);
        $off_y=0;
}
else {
        $width_t=$height_t=$square_size;
        $off_x=$off_y=0;
}

We also need to change the imagecopyresampled function call to add these 2 new variables:

imagecopyresampled($thumb_p, $thumb, $off_x, $off_y, 0, 0, $width_t, $height_t, $width, $height);

The new thumbnail look like this:
danut3
It’s better, the last thing I want is to set a white background to the thumb and I’m done. By default imagecreatetruecolor is creating a black canvas with no parameter to change it to white. In order to do this we need to declare a white background and fill the canvas with it BEFORE adding the scaled image:

$bg = imagecolorallocate ( $thumb_p, 255, 255, 255 );
imagefill ( $thumb_p, 0, 0, $bg );

Now it’s what I want:
danut4

The whole source code is the following:

function set_thumb($file, $photos_dir=‘uploads/photos’,$thumbs_dir=‘uploads/photos/thumbs’, $square_size=167, $quality=100) {
        //check if thumb exists
        if (!file_exists($thumbs_dir."/".$file)) {
                //get image info
                list($width, $height, $type, $attr) = getimagesize($photos_dir."/".$file);
               
                //set dimensions
                if($width> $height) {
                        $width_t=$square_size;
                        //respect the ratio
                        $height_t=round($height/$width*$square_size);
                        //set the offset
                        $off_y=ceil(($width_t$height_t)/2);
                        $off_x=0;
                } elseif($height> $width) {
                        $height_t=$square_size;
                        $width_t=round($width/$height*$square_size);
                        $off_x=ceil(($height_t$width_t)/2);
                        $off_y=0;
                }
                else {
                        $width_t=$height_t=$square_size;
                        $off_x=$off_y=0;
                }
                               
                $thumb=imagecreatefromjpeg($photos_dir."/".$file);
                $thumb_p = imagecreatetruecolor($square_size, $square_size);
                //default background is black
                $bg = imagecolorallocate ( $thumb_p, 255, 255, 255 );
                imagefill ( $thumb_p, 0, 0, $bg );
                imagecopyresampled($thumb_p, $thumb, $off_x, $off_y, 0, 0, $width_t, $height_t, $width, $height);
                imagejpeg($thumb_p,$thumbs_dir."/".$file,$quality);
                }
}

*Note: Nobody was hurt during this tutorial. The cute dude is Razvan‘s son, Danut.

Read also:

Tags: , , , , ,
25 Responses to “Thumbnail generation with PHP tutorial”
  1. RazvanNo Gravatar says:

    The tutorial is very good, but the kid is awesome!!….:)

  2. DominikNo Gravatar says:

    Good tutorial but I wonder why did you use GD instead of Image Magic’s convert library which is faster ?

  3. andreiashNo Gravatar says:

    GD is out-of-the-box, bundled with PHP, compared with ImageMagick which needs to be installed separately. More than this, on the server where I needed this function it was just GD available.

  4. Andrei DANEASA's Blog » Thank you ZendEditor ! says:

    […] « Thumbnail generation with PHP tutorial Jan 14 2009 […]

  5. RobinNo Gravatar says:

    Whats wrong with implementing existing libraries that do just this?
    I’m a strong believer of fixing it yourself to know the ins and outs, but also leaving the wheel as is and just plain using it…

    I.e. phpThumb is a simple library which does what you want and more 🙂

    Or did i miss something in your requirements?

  6. HarroNo Gravatar says:

    We have something similair.. but it just does it when an image of a certain size is requested.
    Whe ran into problems when someone uploaded 500 photo’s and viewed them all… PHP ran out of memory.

    GD is nice enough, but the memory consumption is just insane.. so we installed imagick and rewrote the whole thing.
    Besides it being faster and using less memory, it also gives you way more nice little effects to play with (rounded corners becomes easy peasy for instance).

  7. Non_ENo Gravatar says:

    Hello,
    it is a nice tutorial. At first glance it looked for me like you were trying to hack around thumbnail css centering in the box 🙂 I hope it is not the case.

    Harro: In my previous job we came to conclusion that thumbnail generation of vendor images must be done in batch upon the upload. We chose periodic cron invoked batch (mainly for it’s simplicity). When thumbnails get generated, each image’s database record is marked so that the image is published. It is worth noting that locking is necessary to prevent concurrent batches.

  8. Revue de presse | Simple Entrepreneur says:

    […] Thumbnail generation with PHP tutorial Un tutorial plutôt complet sur l’extension GD de Php qui permet de manipuler des images. L’auteur montre ici comment redimensionner des images, créer des vignettes carrées à partir de ces images, leur ajouter une couleur de fond, … […]

  9. olloNo Gravatar says:

    nice, but i’m wondering why you let gd do the work that the browser should do

  10. andreiashNo Gravatar says:

    Ollo, I don’t get it. Maybe you can clarify… IMHO the browser shouldn’t load a 1MB photo just to scale it at 10%, what actually a thumb is done for…
    but maybe I got it wrong…

  11. daveNo Gravatar says:

    great work ! but i want to ask you. How can i display thumbnail image without saving in a folder.

  12. Personal blog of Yzmir Ramirez » Advanced Thumbnail Trickery with PHP says:

    […] the image background. He managed it all using PHP’s GD extension and he’s written a tutorial explaining how he did it, together with illustrative source code. An interesting read, for those looking to add even more […]

  13. LorenzoNo Gravatar says:

    Thanks for your help. Your function is what I neeeded.

  14. DaveNo Gravatar says:

    is it possible to make the background transparent?

  15. php thumbnailerNo Gravatar says:

    that looks very nice and was very helpful, thank you!

  16. JeanNo Gravatar says:

    Excellent, thanks.

  17. yehielNo Gravatar says:

    I do not understand how i call this function …?

  18. BinojNo Gravatar says:

    Hi,

    Nice article, Im trying to create thumnails with fixed rectangular size for eg; w: 279 x h:183

    Will this apply to this size? Can you tell what i need to change to use this? Iam currently using my gd based code but it scales the image.

    Thanks
    Binoj

  19. HenryNo Gravatar says:

    I usually resize photos using Office picture manager before using it in a web. But this one is a good process.

  20. Mike PNo Gravatar says:

    Nice script! which file types will this work with?

  21. PHP GD – resizing image frame/canvas but not the actual image | PHP Developer Resource says:

    […] can see here: Thumbnail generation with PHP tutorial Tagged: gdimage-processingPHP5questions /* * * CONFIGURATION VARIABLES: EDIT BEFORE […]

  22. PHP increase canvas size of image and save as png with transparent background | Jisku.com - Developers Network says:
  23. Creating Thumbnails Using PHP | asc_Blog says:

    […] Creating Thumbnails Using PHP Leave a reply Sometimes we need to create thumbnails automatically, e.g. from images submitted by users. In this example I’m going to show a simple PHP script on how to create a thumbnail from an image. My example is a modified version of this thumbnail generation tutorial by Andrei Daneasa. […]

  24. radhaNo Gravatar says:

    Hi,

    Can you please help me for generate thumb image resizing with different width & height. I need to resize a image with 250*350 proportion. How to do that. And also support upload any image(.jpg/.png) . Please help me.

Trackbacks
  1. hacking tutorials says:

    hacker news…

    […]Thumbnail generation with PHP tutorial – Andrei DANEASA[…]…

Leave a Reply