How to create thumbnails with PHP and gd

How to make sure your server can generate images

This small article will explain how you create a thumbnail from an image in PHP. Furthermore you learn how to batch process a whole folder of images and create their thumbnails.

To create images with PHP you need to have the gd image library installed and activated in your PHP.

To make sure if gd is installed on your machine, simply check your php info. Create a file that contains:

<?phpinfo()?>

and save it as "test.php" on your server. When you open it in a browser you see a colourful table showing all the schematics of your PHP install. In it you have to find something like this: Example of a php with gd installed

If you know for sure that there is gd on the machine but PHP does not recognise it, it may still be commented in the php.ini.

Scan your machine for the php.ini and edit it in a text editor. You will find loads of extensions:

;extension=php_fdf.dll
;extension=php_filepro.dll
;extension=php_gd.dll
;extension=php_gettext.dll
;extension=php_hyperwave.dl

Simply remove the ";" in front of the php_gd and restart your server.

;extension=php_fdf.dll
;extension=php_filepro.dll
extension=php_gd.dll
;extension=php_gettext.dll
;extension=php_hyperwave.dl

The logic of batch processing thumbnails

Your server is running PHP, gd support is enabled, let's start thinking about the code.

To generate thumbnails we do the following:

  • Scan a folder for JPG and PNG files (gd does not support GIF anymore, because the packing algorithm in GIF is copyrighted).
  • Take each of these images, and load it.
  • Resize the image.
  • Save the image as a thumbnail.

The resizing idea is the following:

  • We assume the thumbnail should be 100 pixels, either wide or high.
  • We load the original image, and check its dimensions.
  • If the picture is higher than wide, we set the height of the thumb to 100 pixels.
  • The width of the thumbnail is the original width multiplied with 100 pixels divided by its height.
  • Thumbnail height = original width * (100 / original height)
  • This way we preserve the original aspect ratio.
  • If the original picture is wider than high, we do the same to the height of the thumbnail.
  • If they are the same, we simply create a 100x100 pixels image.

The PHP functions to use

PHP has a whole lot of functions to help us with generating graphics with gd.

The ones we need to use here are:

  • imageCreateFromJPEG() to create a copy to work on of a .jpg image.
  • imageCreateFromPNG() to create a copy to work on of a .png image.
  • imageSX() to get the width of the original image.
  • imageSY() to get the height of the original image.
  • ImageCreateTrueColor() to create a new truecolour image object.
  • imageCopyResampled() to resample the image.

GD supports truecolour images from version 2.0 onwards, older versions of GD will create JPGs and PNGs with 256 colours and need other functions. I deliberately dropped the support here, as gd2 comes bundled with every newer install of PHP anyways.

  • imageJPEG() to create a new JPEG image.
  • imagePNG() to create a new PNG image.
  • imagedestroy() to delete the old image objects in the memory.

Furthermore I created some functions I keep using:

  • directory() reads a folder and returns all the files that apply to a certain filter.
  • ditchtn() clears the resulting array from all files starting with a filter you define, like tn_".
  • createthumb() creates a thumbnail and saves it to the server.

directory() and ditchtn() are filesystem and array functions, I will not explain them here, they should be pretty self-explanatory.

The main thumbnail generation function

createthumb() is the main thumbnail generation function, so let's take a closer look:

function createthumb($name,$filename,$new_w,$new_h){
	$system=explode('.',$name);
	if (preg_match('/jpg|jpeg/',$system[1])){
		$src_img=imagecreatefromjpeg($name);
	}
	if (preg_match('/png/',$system[1])){
		$src_img=imagecreatefrompng($name);
	}

createthumb() is called with the following parameters: The name of the original image (if needed with folder name), the name of the thumbnail picture, and the dimensions.

These lines get the information if gd is at least version 2.0 and check if the original image is a JPEG or PNG.

Accordingly, a new image object is created called src_image.

	
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
	$thumb_w=$new_w;
	$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
	$thumb_w=$old_x*($new_w/$old_y);
	$thumb_h=$new_h;
}
if ($old_x == $old_y) {
	$thumb_w=$new_w;
	$thumb_h=$new_h;
}

These lines get the dimensions of the original image by using imageSX() and imageSY(), and calculate the dimensions of the thumbnail accordingly, keeping the correct aspect ratio. The desired dimensions are stored in thumb_w and thumb_h.

	$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 

These lines create the image as a true colour version using ImageCreateTrueColor() and resize and copy the original image into the new thumbnail image, on the top left position.

	
if (preg_match("/png/",$system[1]))
{
	imagepng($dst_img,$filename); 
} else {
	imagejpeg($dst_img,$filename); 
}
imagedestroy($dst_img); 
imagedestroy($src_img); 
}

These lines check the file system extension of the original image and create the thumbnail accordingly. The thumbnail gets saved onto the server (by adding a filename to imagejpeg() or imagepng() function) and the two image objects get destroyed to free the memory.

How to use createthumb()

Let's say you have an original picture called apple.jpg in a folder pics and you want to generate the thumbnail in the folder thumbs as tn_apple.jpg 100x100 pixels big.

You can do this by calling this function with the following parameters:

createthumb('pics/apple.jpg','thumbs/tn_apple.jpg',100,100);

To batch process all the pictures in the folder pics and generate their thumbnails in the folder thumbs you do the following:

$pics=directory('pics','jpg,JPG,JPEG,jpeg,png,PNG');
$pics=ditchtn($pics,'tn_');
if ($pics[0]!='')
{
	foreach ($pics as $p)
	{
		createthumb('pics/'.$p,'thumbs/tn_'.$p,100,100);
	}
}

You grab all the pictures from the pics folder via directory() and a filter for images.

Then you delete all the thumbnails by using ditchtn() and make sure that the resulting array is not empty.

The second parameter in ditchtn() must match the name you give your thumbnails, this is done to prevent thumbnails being generated from thumbnails.

You then loop over all images and generate the thumbnail with the desired dimensions and names.

Caveats and download

Generating thumbnails with PHP is pretty handy and saves you a lot of time pushing files onto your server via FTP. It also makes it easier to keep a image gallery up to date.

Using the functions introduced here it is no problem to scan a folder for new images and create the thumbnails when new images were uploaded.

PHP with gd can be very slow at times though, especially when the machine is not too fast and the resample() function is used. Some servers might stop telling you the maximum time of script execution has been not enough. You can change this in your php.ini:

max_execution_time = 320 ; Maximum execution time of each script, in seconds

Now, try to generate some thumbnails on your own server by playing with the thumbnail generator, a script that has all the functions described above included.