Thursday, November 5, 2009

Creating Thumbnail in PHP

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    =    'large.jpg';
$destPath    =    'thumb.jpg';
$maxwidth    =    250;
$maxheight   =    150;
createThumb($filePath,$destPath,$maxwidth,$maxheight);

echo 'Thumbnail Created.';
?>

No comments: