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?
… and what we want to achieve:

First step would be the thumbnail generation snippet:
$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:
As we can see, the photo is distorted and we need to scale it, by adding 2 variables:
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:
The new result would be:
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.
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:
The new thumbnail look like this:
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:
imagefill ( $thumb_p, 0, 0, $bg );
Now it’s what I want:
The whole source code is the following:
//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:
The tutorial is very good, but the kid is awesome!!….:)
Good tutorial but I wonder why did you use GD instead of Image Magic’s convert library which is faster ?
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.
[…] « Thumbnail generation with PHP tutorial Jan 14 2009 […]
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?
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).
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.
[…] 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, … […]
nice, but i’m wondering why you let gd do the work that the browser should do
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…
great work ! but i want to ask you. How can i display thumbnail image without saving in a folder.
[…] 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 […]
Thanks for your help. Your function is what I neeeded.
is it possible to make the background transparent?
that looks very nice and was very helpful, thank you!
Excellent, thanks.
I do not understand how i call this function …?
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
I usually resize photos using Office picture manager before using it in a web. But this one is a good process.
Nice script! which file types will this work with?
[…] can see here: Thumbnail generation with PHP tutorial Tagged: gdimage-processingPHP5questions /* * * CONFIGURATION VARIABLES: EDIT BEFORE […]
[…] http://www.webxpert.ro/andrei/2009/01/08/thumbnail-generation-with-php-tutorial/ […]
[…] 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. […]
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.