March 9, 2008

PHP Thmbnail Function

I had whipped up a online photo album for the AMS website I am working on, however after photos where uploaded I realized that I was not using thumbnails, but instead the huge pictures, which on dial up would take years to load a large album. So I went looking for a good thumbnail function, sadly all the ones I found where way to complex for what I was trying to do. With no other options, I did some research and studied how the other functions worked an came up with my own simple version.


function makeThumb($im,$dest,$thumbwidth,$thumbheight)
{
$resizeResult = TRUE;
$imgResult = TRUE;

list($width, $height) = getimagesize($im);
$exttype = exif_imagetype($im);

$tim = ImageCreateTrueColor($thumbwidth,$thumbheight);

if($exttype == IMAGETYPE_GIF)
{
$image = imagecreatefromgif($im);
imagealphablending($tim, FALSE);
imagesavealpha($tim, TRUE);
$resizeResult = imagecopyresampled($tim, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height);
//header('Content-type: image/gif');
$imgResult = imagegif($tim,$dest);
}
else if($exttype == IMAGETYPE_JPEG)
{
$image = imagecreatefromjpeg($im);
$resizeResult = imagecopyresampled($tim, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height);
//header('Content-type: image/jpeg');
$imgResult = imagejpeg($tim,$dest);
}
else if($exttype == IMAGETYPE_PNG)
{
$image = imagecreatefrompng($im);
imagealphablending($tim, FALSE);
imagesavealpha($tim, TRUE);
$resizeResult = imagecopyresampled($tim, $image, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height);
//header('Content-type: image/png');
$imgResult = imagepng($tim,$dest);
}

if($resizeResult != TRUE || $imgResult != TRUE){ return FALSE; } else return TRUE;
}


To use just call makeThumb("Location of Image", "Place to put thumbnail", width, height); Very simple, also it will return false if something fails inside. Remember to make sure the directory it is writing to has the permission to write set correctly or it will always fail.

No comments: