Create an image on the fly with the GD library

Last Updated on: March 13, 2023

If your website has a lot of images it is often convenient to create and show a dynamic thumbnail image. This will save on processor and download time for your visitors, who only have to download the images they want to see. One great way to do this is with the GD library.

Before you start, ensure the GD Library runs as part of your PHP installation.

One great function in the GD Library is Imagecopyresized(). This takes a source image and converts it to a destination image of the required size and in the desired position on the screen.

// The source file
$file = 'image.jpg';

// Sets the output to 45% of the original size
$size = 0.45;

// Sets the output to be a jpeg
header('Content-type: image/jpeg');

//Sets the resize values
list($width, $height) = getimagesize($file);
$modwidth = $width * $size;
$modheight = $height * $size;

// Create the image canvas
$tn= imagecreatetruecolor($modwidth, $modheight);
$source = imagecreatefromjpeg($file);

// Resizes our image to fit the canvas
imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);

// Produces the output jpeg
imagejpeg($tn);

If the image this produces is not good enough for your purposes, then you can try using imagecopyresampled(). The inputs are the same as imagecopyresized(), and the above example would work with just this line changed:

imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);

Once you have created your thumbnail, you can either save it or use it directly in the .php file. You can link to it just as you would any other graphic file:

<img src="MyThumbNail.php" />

Alternatively, save it through the imagejpeg() function. This also works for gif or png format images. This example demonstrates how it works:

// Name you want to save your files as
$save = 'myfile.jpg';
$file = 'original.jpg';
echo "Creating file: $save";
$size = 0.45;
header('Content-type: image/jpeg') ;
list($width, $height) = getimagesize($file) ;
$modwidth = $width * $size;
$modheight = $height * $size;
$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;

// Saves the jpeg you created above
imagejpeg($tn, $save, 100) ;

Get notified of new posts:


Similar Posts

Leave a Reply

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