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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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:
1 2 |
$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.