How To Generate Thumbnails On The Fly With PHP
There are two great ways to generate thumbnails for images on the fly with PHP:
- Use GD to resize the image on the fly and output it
- Extracts the thumbnail from the Exif data. (If this fails, you could revert to method 1 above.)
The latter assumes that the image file has exif data, which most photos do. To ensure the fastest loading thumbnails it would be best to generate thumbnails when images are uploaded to the server, but there are times when you don’t want to have to store thumbnails for every image uploaded.
Method 1: Using GD To Resize On The Fly
Using this 8.5MB image, and the code below, the following URL will load a thumbnail that is dynamically created: http://www.incero.com/codesamples/thumbnailonthefly/thumbnail.php?image=highres.jpg&width=160
<?php
/*How to extract a thumbnail from Exif data using PHP
Created by Gordon Page, gordon@incero.com. April 30th, 2010.
Incero.com offers custom coding and hosting solutions.
*/
header("Content-type: image/jpeg");
// get image size
$file = $_GET[image];
if($size = GetImageSize($file)){
$w = $size[0];
$h = $size[1];
//set new size
$nw = $_GET['width'];
$nh = ($nw*$h)/$w;
}
else{
//set new size
$nw = "160";
$nh = "120";
}
//draw the image
$src_img = imagecreatefromjpeg($file);
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $nw, $nh, $w, $h);//resizing the image
imagejpeg($dst_img,"",100);
imagedestroy($src_img);
imagedestroy($dst_img);
?>
You’ll notice that with this method it takes about a second to generate the thumbnail so you may want to default to the method below which is faster, and if that method fails then fall back to this first method.
Method 2: Extracting The Thumbnail From The Exif Data
Using the same 8.5MB image, and the code below, the following URL will extract the thumbnail from the Exif data: http://www.incero.com/codesamples/thumbnailonthefly/exifthumb.php?image=highres.jpg
<?php
/*How to extract a thumbnail from Exif data using PHP
Created by Gordon Page, gordon@incero.com. April 30th, 2010.
Incero.com offers custom coding and hosting solutions.
*/
// file to read
$file =$_REQUEST['image'];
$image = exif_thumbnail($file, $width, $height, $type);
// width, height and type get filled with data
// after calling "exif_thumbnail"
if ($image) {
// send header and image data to the browser:
header('Content-type: ' .image_type_to_mime_type($type));
print $image;
}
else {
// there is no thumbnail available, handle the error.
//This would be a great place to revert to the GD resize method.
print 'No thumbnail available';
}
?>
Feel free to use the code above in your own projects. If you are in need of paid programming services please contact us.

I did not know that you could extract the thumbnail from the EXIF data using GD, I took your script above and edited my photo hosting site to check if a thumb exists in EXIF before performing the more CPU intensive re-size method. Thanks.