Create an image on the fly with the GD library

by jeremyjones on March 8, 2011

  • Share
  • CevherShare
  • Share

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 and they only have to download the images they want to see. One great tool to do this is the GD library. Before you start, make sure that 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 screen.

<?php
// 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 exactly 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:

<?php
//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) ;
?>

Leave a Comment

Previous post:

Next post: