PHP Thumbnail Generator

You can use this script as the location for your image and it will generate a thumbnail.


You can then link back to the original image, no need to use a graphics editor to create thumbnails for you. This script is also used in my PHP Gallery and in the Picasa Gallery to generate thumbnails as needed.

Once they are generated they are read from file, and they can also be cached to save your site some bandwidth. It uses the PHP GD library which is installed on most web host, you can get fancier thumbnails with Image Magick but I haven't found a host that offers it for free.

It's important for me that the thumbnails were only generated as they are requested by a page since I'm using a free web hosts and they put a cap on how much CPU cycle you can use. And image processing takes a lot of CPU cycles so I try to convserve it if I could.


 * PHP thumbnail generator
 * Generates on the fly thumbnails
 * @author Herbert Balagtas
 * @example <img src="images/thumbnail.php?filename=image1.jpg" />

define('THUMBNAIL_PATH', '');
define('LOCAL_GALLERY_PATH', '');
define('THUMBNAIL_HEIGHT', 150);

include_once ('../gallery/myfunctions.php');

$filename = decode_string($_GET['filename']);
$path = decode_string($_GET['path']);
#$picture = LOCAL_GALLERY_PATH . '/' . $path . '/' . $filename;
$picture = $filename;
#$thumbfile = implode_dir(array(THUMBNAIL_PATH, $path)) . '/TN_' . $filename;
$thumbfile = 'TN_' . $filename;

/*if (!is_dir(THUMBNAIL_PATH . $path)) {
	$paths = explode ('/',$path);
	foreach($paths as $p){
		$pp[] = $p;
		$pdir = implode('/',$pp);
		@mkdir (THUMBNAIL_PATH . $pdir);


if (!file_exists($thumbfile)){
	$picture = open_image ( $picture );
	if ($picture === false) die ('Unable to open image');

	/*$new_width = THUMBNAIL_WIDTH;
	$width = imagesx($picture);
	$height = imagesy($picture);
	$new_height = $height * ($new_width/$width);*/

	$new_height = THUMBNAIL_HEIGHT;
	$width = imagesx($picture);
	$height = imagesy($picture);
	$new_width = $width * ($new_height/$height);

	$image_resized = imagecreatetruecolor($new_width, $new_height);
	fastimagecopyresampled($image_resized, $picture, 0, 0, 0, 0, $new_width, $new_height, $width, $height, 3);
	imageinterlace ( $image_resized, 1);
	imagejpeg ( $image_resized, $thumbfile );

	imagedestroy( $picture );

#header("Pragma: ");// leave blank to avoid IE errors
header('Content-type: image/jpeg');
header('Cache-Control: max-age=2592000, must-revalidate');
header( "Content-Disposition: inline; filename=\"TN_" . $filename . '"' );
if (!$image_resized){
} else {
	imagedestroy( $image_resized );

Personal Links

Favorite Links