04 November 2008

PHP - Image Resizer

///////////////////////////////////////// IMAGE RESIZER STARTS/////////////////////////////////////////////////////
function resize_img($imgPath, $maxWidth, $maxHeight, $directOutput = true, $quality = 90, $verbose,$imageType)
{
// get image size infos (0 width and 1 height,
// 2 is (1 = GIF, 2 = JPG, 3 = PNG)
$size = getimagesize($imgPath);
// break and return false if failed to read image infos
if(!$size)
{
if($verbose && !$directOutput)echo "
Not able to read image infos.
";
return false;
}
// relation: width/height
$relation = $size[0]/$size[1];
$relation_original = $relation;

// maximal size (if parameter == false, no resizing will be made)
$maxSize = array($maxWidth?$maxWidth:$size[0],$maxHeight?$maxHeight:$size[1]);
// declaring array for new size (initial value = original size)
$newSize = $size;
// width/height relation
$relation = array($size[1]/$size[0], $size[0]/$size[1]);
if(($newSize[0] > $maxWidth))
{
$newSize[0]=$maxSize[0];
$newSize[1]=$newSize[0]*$relation[0];
}
if(($newSize[1] > $maxHeight))
{
$newSize[1]=$maxSize[1];
$newSize[0]=$newSize[1]*$relation[1];
}
switch($size[2])
{
case 1:
if(function_exists("imagecreatefromgif"))
{
$originalImage = imagecreatefromgif($imgPath);
}
else
{
if($verbose && !$directOutput)echo "
No GIF support in this php installation, sorry.
";
return false;
}
break;
case 2: $originalImage = imagecreatefromjpeg($imgPath); break;
case 3: $originalImage = imagecreatefrompng($imgPath); break;
case 6: $originalImage = imagecreatefromwbmp($imgPath); break;
default:
if($verbose && !$directOutput)echo "
No valid image type.
";
return false;
}
// create new image
$resizedImage = imagecreatetruecolor($newSize[0], $newSize[1]);
imagecopyresampled($resizedImage, $originalImage,0, 0, 0, 0,$newSize[0], $newSize[1], $size[0], $size[1]);
$rz=$imgPath;
if($directOutput)
imagejpeg($resizedImage);
else
{
$rz=preg_replace("/\.([a-zA-Z]{3,4})$/","".$imageType.".jpg", $imgPath);
imagejpeg($resizedImage, $rz, $quality);
}
// return true if successfull
return $rz;
}
////////////////////////////////////////// IMAGE RESIZER ENDS////////////////////////////////////////////////////////
////////////////////////////////////////////HOW TO USE IT START//////////////////////////////////////////////////////
Rename the uploaded image with ".jpg" ext.
resize_img2($IMGPATH, 562 , 319, false, 100, 0,"");
////////////////////////////////////////////HOW TO USE IT END//////////////////////////////////////////////////////

No comments: