December 15, 2008

PHP resize image

Here is the function which you can resize your image by call it like this:
<img src="resize_pic.php?name='.$photo.'&width=500&height=500" border="0" />
======================================
resize_pic.php
-------------------------------------------
function Resize($Dir,$Image,$MaxWidth,$MaxHeight) {
list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
$ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":($TypeCode==3?"png":FALSE)));
$CreateFunction="imagecreatefrom".$ImageType;
$OutputFunction="image".$ImageType;
if ($ImageType) {
$RatioHeight=($ImageHeight/$ImageWidth);
$RatioWidth=($ImageWidth/$ImageHeight);
$ImageSource=$CreateFunction($Dir.$Image);
if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
if ( $MaxWidth <= $ImageWidth && $ImageWidth >= $ImageHeight) {
$ResizedWidth = $MaxWidth;
$ResizedHeight = $ResizedWidth*$RatioHeight;
}else if ( $MaxHeight <= $ImageHeight && $ImageHeight >= $ImageWidth) {
$ResizedHeight = $MaxHeight;
$ResizedWidth = $ResizedHeight*$RatioWidth;
}else{
$ResizedWidth = $ImageWidth;
$ResizedHeight = $ImageHeight;
}
$ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth, $ResizedHeight,$ImageWidth,$ImageHeight);
}else {
$ResizedWidth=$ImageWidth;
$ResizedHeight=$ImageHeight;
$ResizedImage=$ImageSource;
}
$OutputFunction($ResizedImage);
return true;
}else
return false;
}

$name = $_GET["name"];
$width = $_GET["width"];
$height = $_GET["height"];
$dir = "images/image_for_estate/";
Resize($dir,$name,$width,$height);