Creating thumbnails dynamically from images with PHP

Managing large gallerias or photo albums in dynamic web services needs thumbnails to be created on fly. In PHP there are built in functions which can create thumbnails at run time with given width but for more requirements like creating thumbnails with custom provided values for top, left and more supported image formats like png, gif we can use phpThumb. 

First we will create a simple function to create thumbnail from image with PHP.
function createThumbnail($src, $destination, $width) {

	$image = imagecreatefromjpeg($src);
	$imgW = imagesx($image);
	$imgH = imagesy($image);
	
	$height = floor($imgH * ($width / $imgW));
	$thumb = imagecreatetruecolor($width, $height);
	
	imagecopyresampled($thumb, $image, 0, 0, 0, 0, $width, $height, $imgW, $imgH);
	
	imagejpeg($thumb, $destination);
}
This function will create thumbnail with provided width. Now we will write function with more requests to generate thumbnail. To use this function we will need phpThumb library you can download this library from here
include("phpThumb/phpthumb.class.php");
function createThumbnail($imagePath,$filename,$destPath,$width,$height,$left,$top,$zc=1) {
	
	$imgName = explode('.', $filename);
	$EXT = $imgName[1];
	$capture_raw_data = false;
	$phpThumb = new phpThumb();
	$phpThumb->setSourceFilename($imagePath.$filename);
	$phpThumb->setParameter('sw', $width);
	$phpThumb->setParameter('sh', $height);
	
	$phpThumb->setParameter('sx', $left);
	$phpThumb->setParameter('sy', $top);
	$phpThumb->setParameter('zc', $zc);
	
	if(!is_dir($destPath)) {
		@mkdir($destPath, 0777);
	}
	$phpThumb->setParameter('config_output_format', $EXT);
	$phpThumb->setParameter('config_imagemagick_path', '/usr/local/bin/convert');

	if ($phpThumb->GenerateThumbnail()) {

		if ($phpThumb->RenderToFile($destPath.$filename)) {
		} else {
		}
	} else {
	}
}
Share your views about how you find this post useful.
Tags: Thumbnails
comments powered by Disqus