PHP Image Resizing Function
April 1st, 2011
As speed is paramount to website efficiency, image re-sizing is a useful function for generating cached versions of images. The following allows you to define:-
- The source file (realpath)
- A destination filename (realpath)
- Maximum width (pixels)
- Maximum height (pixels)
It maintains the aspect ratio and automatically calibrates how to scale down high resolution images to the desired proportion.
public function imageResize($source, $dest, $maxWidth, $maxHeight)
{
$is = getimagesize($source);
$fw = (true || $is[0] >= $is[1]) ? $maxWidth : $maxHeight;
$fh = (true || $is[0] >= $is[1]) ? $maxHeight : $maxWidth;
$orientation = ($is[0] >= $is[1]) ? 0 : 1;
$iw = $is[0];
$ih = $is[1];
$t = 2;
if ($is[0] > $fw || $is[1] > $fh)
{
if ($is[0] - $fw >= $is[1] - $fh)
{
$iw = $fw;
$ih = ($fw / $is[0]) * $is[1];
}
else
{
$ih = $fh;
$iw = ($ih / $is[1]) * $is[0];
}
$t = 1;
}
switch ($t)
{
case 1:
$src = imagecreatefromjpeg($source);
$dst = imagecreatetruecolor( $iw, $ih );
imagecopyresampled($dst, $src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1]);
return imagejpeg($dst, $dest, 90);
break;
case 2:
return copy($source, $dest);
break;
default:
return false;
break;
}
}
Article written by