Thumbnail are used by graphic designers and photographers for a small image representation of a larger image. The main advantage of creating thumbnails is that it generates the new image with the proportional dimension of the large image and hence the image resolution and quality remain intact. As the thumbnails are smaller in size they load quickly and makes the page render faster as well.

We are using a thumbnail class to make code simpler and easy to use. Image extensions with jpg, gif and png are supported for creating thumbnail using this class.

Three easy steps to create and image thumbnail :

Step 1. Create a folder and named  as createThumb.  Create a file named thumbnail_Class.php in the createThumb folder and paste the code given below into it.

<?
function createThumb($srcname,$destname,$maxwidth,$maxheight)
{
$oldimg = $srcname;
$newimg = $destname;

list($imagewidth,$imageheight,$imagetype)=@getimagesize($oldimg);

$shrinkage = 1;
if ($imagewidth > $maxwidth)
$shrinkage = $maxwidth/$imagewidth;
if($shrinkage !=1)
{
$dest_height = $shrinkage * $imageheight;
$dest_width = $maxwidth;
}
else
{
$dest_height=$imageheight;
$dest_width=$imagewidth;
}
if($dest_height > $maxheight)
{
$shrinkage = $maxheight/$dest_height;
$dest_width = $shrinkage * $dest_width;
$dest_height = $maxheight;
}
if($imagetype==2)
{
$src_img = imagecreatefromjpeg($oldimg);
$dst_img = imagecreatetruecolor($dest_width, $dest_height);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $imagewidth, $imageheight);
imagejpeg($dst_img, $newimg, 75);
imagedestroy($src_img);
imagedestroy($dst_img);
}

elseif ($imagetype == 3)
{
$src_img = imagecreatefrompng($oldimg);
$dst_img = imagecreatetruecolor($dest_width, $dest_height);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $imagewidth, $imageheight);
imagepng($dst_img, $newimg, 75);
imagedestroy($src_img);
imagedestroy($dst_img);
}
else
{
$src_img = imagecreatefromgif($oldimg);
$dst_img = imagecreatetruecolor($dest_width, $dest_height);
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $dest_width, $dest_height, $imagewidth, $imageheight);
imagegif($dst_img, $newimg, 75);
imagedestroy($src_img);
imagedestroy($dst_img);
}
}
?>

Step 2. Create a file named index.php with in this folder and paste the code given below inside index.php. This is the file which you need to run from the browser. Place your image (e.g., grapes.jpg) to create thumbnail within the createThumb folder.

<?
include(‘thumbnail_Class.php’);

$filePath    =    ‘grapes.jpg’;
$destPath    =    ‘Thumb_grapes.jpg’;
$maxwidth        =    450;
$maxheight        =    300;
createThumb($filePath,$destPath,$maxwidth,$maxheight);

echo ‘Thumbnail Created.’;
?>

Step 3. Finally, Run the index.php from your browser and if your thumbnail is created successfully then you will get an message “Thumbnail Created” and the thumnail image will create in createThumb folder with name Thumb_grapes.jpg.