This function will resize an image to the specified width and height without distorting it and in most cases without adding black regions to the image (by cropping the image to the desired size). It is very useful for creating picture thumbnails of a given size, regardless of the image’s original dimensions.
/*
function ResizeProportionalImage($nw, $nh, $source, $stype, $dest=”)
$nw = new Width
$nh = new Height
$source = path to source image (it can be JPG, PNG or GIF)
$stype = image type (JPG, PNG or GIF)
$dest = image destination. If set, the image will be stored at the given location (as a JPG image). If not set, the function will return a GD image.
*/
function ResizeProportionalImage($nw, $nh, $source, $stype, $dest=”)
{
$size = getimagesize($source);
$w = $size[0];
$h = $size[1];
switch($stype)
{
case IMAGETYPE_GIF:
$simg = imagecreatefromgif($source);
break;
case IMAGETYPE_JPEG:
$simg = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$simg = imagecreatefrompng($source);
break;
}
$dimg = imagecreatetruecolor($nw, $nh);
$wm = $w/$nw;
$hm = $h/$nh;
$h_height = $nh/2;
$w_height = $nw/2;
if($w> $h)
{
$adjusted_width = $w / $hm;
$half_width = $adjusted_width / 2;
$int_width = $half_width – $w_height;
imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
}
elseif(($w <$h) || ($w == $h))
{
$adjusted_height = $h / $wm;
$half_height = $adjusted_height / 2;
$int_height = $half_height – $h_height;
imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
}
else
{
imagecopyresampled($dimg,$simg,0,0,0,0,$nw,$nh,$w,$h);
}
if($dest!=”)
imagejpeg($dimg,$dest,100);
else
return $dimg;
}


Example: ResizeProportionalImage(300, 250, ‘./image-resize-original.jpg’, IMAGETYPE_JPEG, ‘./image-resized.jpg’); when applied to the image on the left would produce the image on the right.





No user commented in " Resize image proportionally (cropping it if necessary) "
Follow-up comment rss or Leave a Trackback