Sometimes restricting images size is required. Following function is very useful to create images of certain sizes on the fly
function createThumbs($source, $dest, $requiredWidth, $requiredHeight, $fileType='')
{
$size = getimagesize($source);
$givenWidth = $size[0];
$givenHeight = $size[1];
if ($givenWidth > 800)
{
$requiredRatio = $requiredWidth / $requiredHeight;
$middleWidth = ceil($givenHeight * $requiredRatio);
if($middleWidth>$givenWidth){
$requiredRatio = $requiredHeight / $requiredWidth;
$middleHeight = ceil($givenWidth * $requiredRatio);
$middleWidth = $givenWidth;
$y = ceil(($givenHeight - $middleHeight)/2);
}
else{
$middleHeight = $givenHeight;
$middleWidth = ceil($givenHeight * $requiredRatio);
$x = ceil(($givenWidth - $middleWidth)/2);
}
$new_im = imagecreatetruecolor($requiredWidth,$requiredHeight);
$extention = strtolower(substr($source, strlen($source)-3, strlen($source)));
if ($extention == "jpg" || $extention == "jpeg") { $im = imagecreatefromjpeg($source); }
elseif ($extention == "gif") { $im = imagecreatefromgif($source); }
elseif ($extention == "png") { $im = imagecreatefrompng($source); }
else
{
//echo("ERROR: Unknown image source file format");
return;
}
imagecopyresampled($new_im,$im,0,0,$x,$y,$requiredWidth,$requiredHeight,$middleWidth,$middleHeight);
imagejpeg($new_im,$dest,85);
}
}
No comments:
Post a Comment