Dynamically create thumbnails in PHP with GD

Many times we need to use multiple copies of the same image on our sites at different sizes. Instead of having to worry about managing multiple copies of the same image, we can use PHP with the GD library to create thumbnails of our full size images.

The first thing we need to is make sure our web server has GD installed. Create a PHP page and put


inside it and run it on your web server. This will output all the detailed configuration of your PHP build. Look for this in your config:

Make sure GD Support is enabled. Now we’re all set and ready to start making thumbnails. Here is my thumbnail generating script:

//create_thumbnail.php

	//if php runs out of memory on big images, up the memory size
	ini_set("memory_limit","20M");
	
	//set up our image directory
	$dir = "../images/";
	
	//create the file name
	$filename = $dir . $_GET['name'];
	
	//set the thumbnail size
	$type = $_GET['type'];
	
	// 0 = thumb(100 pixels)
	// 1 = featured ad(180 pixels)
	$THUMB = 100;
	$FEATURED = 150;
	
	if($type == 1)
		$scaleWidth = $FEATURED;
	else
		$scaleWidth = $THUMB;
	
	//get the image type (jpg, gif, png)
	$imageInfo = getimagesize($filename);
	$ext = image_type_to_mime_type($imageInfo[2]);
	
	//get the image size
	$imgsize = getimagesize($filename);
	$height = $imgsize[1];
	$width = $imgsize[0];
	
	//set up the scale ratio
	$widthRatio = round($scaleWidth / $width);
	
	//create the image resource
	if($ext == "image/jpeg")
		$orig_image = imagecreatefromjpeg($filename); 
	elseif($ext == "image/png")
		$orig_image = imagecreatefrompng($filename);
	else
		$orig_image = imagecreatefromgif($filename);
	
	//get the new width and height based off the scale ratio	
	$newheight = round($imgsize[1]*$widthRatio);
	$newwidth = $scaleWidth;
	
	//create the new image resource
	$newimage = imagecreatetruecolor($newwidth, $newheight);
	
	//copy the original image to the new image at the scaled size
	imagecopyresized($newimage, $orig_image, 0, 0, 0, 0, $newwidth, $newheight,$width, $height);
	
	//output the new image to the browser
	if($ext == "image/jpeg")
		imagejpeg($newimage,NULL,100);
	elseif($ext == "image/png")
		imagepng($newimage,NULL,100);
	else
		imagegif($newimage,NULL,100);
	
	//destroy the image resource
	imagedestroy($newimage);
	imagedestroy($orig_image);

Lets take a closer look at it:

//if php runs out of memory on big images, up the memory size
	ini_set("memory_limit","20M");
	
	//set up our image directory
	$dir = "../images/";
	
	//create the file name
	$filename = $dir . $_GET['name'];
	
	//set the thumbnail size
	$type = $_GET['type'];
	
	// 0 = thumb(100 pixels)
	// 1 = featured ad(150 pixels)
	$THUMB = 100;
	$FEATURED = 150;
	
	if($type)
		$scaleWidth = $FEATURED;
	else
		$scaleWidth = $THUMB;

First I up the memory of PHP just in case one of my clients uploaded a really big image which the script needs to process. Then I set my image directory. This is relative to where the script is executing from. Now I get the GET variables which I will detail later when I set it up in the IMG tag. Then I set up the width of the thumbnail. I usually need a few different thumbnail sizes so I have two different widths set.

//get the image type (jpg, gif, png)
	$imageInfo = getimagesize($filename);
	$ext = image_type_to_mime_type($imageInfo[2]);
	
	//get the image size
	$height = $imageInfo[1];
	$width = $imageInfo[0];
	
	//set up the scale ratio
	$widthRatio = round($scaleWidth / $width);

Here I get infomation about the image. getimagesize() will grab info about the image, specifically the mime type, width and height. image_type_to_mime_type() will convert the int mime type from getimagesize to the actual string mime type. Now divide the scaleWidth by the image width to get the width ratio will we use to set the proper scaled hieght.

//create the image resource
	if($ext == "image/jpeg")
		$orig_image = imagecreatefromjpeg($filename); 
	elseif($ext == "image/png")
		$orig_image = imagecreatefrompng($filename);
	else
		$orig_image = imagecreatefromgif($filename);
	
	//get the new width and height based off the scale ratio	
	$newheight = round($imgsize[1]*$widthRatio);
	$newwidth = $scaledWidth;

Now it’s time to create the image resource from the image. This is the resource we will use to make our thumb. It creates the resource based on the mime type of the image. If you are working with other image types you can look up the mime types here. The height of the thumbnail is now computed using the ratio that was computed based on the width of the image and the thumbnail.

	//create the new image resource
	$newimage = imagecreatetruecolor($newwidth, $newheight);
	
	//copy the original image to the new image at the scaled size
	imagecopyresized($newimage, $orig_image, 0, 0, 0, 0, $newwidth, $newheight,$width, $width);
	
	//output the new image to the browser
	if($ext == "image/jpeg")
		imagejpeg($newimage,NULL,100);
	elseif($ext == "image/png")
		imagepng($newimage,NULL,100);
	else
		imagegif($newimage,NULL,100);
	
	//destroy the image resource
	imagedestroy($newimage);
	imagedestroy($orig_image);

A new image resource is created for our thumbnail based on the width and heights which we computed. Now imagecopyresized() is used to copy the original image into the new image resource at the scaled width and height that was created. The thumbnail is now created so lets output it to the browser. imagejpeg, imagepng, and imagegif have a couple options. The first parameter is the image resource. The second is a filename if we want to save the thumbnail somewhere. Because I am always creating the thumbnail dynamically, I set it to null. The 3rd parameter is the compression quality of the picture. I have set it to 100% here. Lastly I destroy both image resources to free up the memory used by them.

So that’s it.

Wait how do we actually call the script.

Calling the script is easy. We just use this simple img tag:


The image tag calls the PHP script with the image name as the “name” variable and the “type” variable is set for the proper width wanted.

So where would creating dynamic thumbnails be useful:

  • Photo galleries
  • Product thumbnails used to link to a product page
  • Create thumbnails from uploaded images and save them to a directory (script modifications required)

Update: Directory Structure

It seems like some people are having problem with the directory structure for the create_thumbnails.php script to properly access the original image. For this example the directory structure is as follows:


httpdocs/includes/create_thumbnail.php
httpdocs/images/

So in order for the php script to access the images directory it needs to go up a directory first:

$dir = "../images/";

If you paths differ to this you will need to update this $dir variable accordingly.

Continue Reading

  • No Related Posts
  • Jan

    For some odd reason it doesn’t work. If I point the browser to the create_thumbnails.php with the appropriate GET values, it prints a blank page…

  • Jan

    Same exact version of GD as well. 2.0.3.4 Compatible… 1 and 1 Hosting. PHP Version 5.2.14

  • Skye

    hmmm I just tested it out and it’s working fine for me. Can you send me the URL of your script?
    Make sure the $dir variable for your image directory is set up properly according to the location of the create_thumbnails.php script.

    • David

      how to modify this, because when i call this script i get broken image icons. $dir = “nuotraukos”;

      • Skye

        You need to make sure your directory paths to your images are correct relative to where the create_thumbnails.php is located. See my update at the bottom of this article. You also need a trailing slash on your $dir variable.

        $dir = “nuotraukos/”;

  • Ron1966

    Before writing back the images make sure the directory path is avaible.

    If you call the script from a sub directory use for example $dir = “../nuotraukos/”