opencodez

How to generate image thumbnails in PHP

Thumbnails proves to be very useful in presenting various online and print media. Here I would like to share a simple function to generate image thumbnails in php. I used this a lot for simple presentations.

Supported formats : TIFF, JPEG

function Thumbnail($file,$print=true)
{
   $thumbimage = @exif_thumbnail($file, $width, $height, $type);
   if($thumbimage!==false)
   {
	 if($print)
	 {
	   header('Content-type: ' .image_type_to_mime_type($type));
	   print $thumbimage;
   	 }
   	 else
   	 {
	   $handle = fopen ($path_to_new_file, 'w');
	   fwrite($handle, $thumbimage);
	   fclose($handle);
   	 }
   }
   else
   {
	   print "Could not generate thumbnail.";
   }
}

Usage:

$file = "myimage.jpg";
Thumbnail($file);

Function checks if it can get thumbnail and accordingly sets heigh, width and type parameters. As you can see function can either print the thumbnail or create new image file.