Thursday, June 23, 2011

How to fit an image in a rectangle area in PHP using GD

Have you ever had a fixed space in your design, and you must put an image that fits exactly there, while preserving the aspect ratio? Well, this is what i'll explain in this article.
Let's say we have this image:

To fit this image in a 100x100 box while keeping the image aspect ratio, we have 2 options:
The first (and most used) is to resize and crop it.

If we have a image resource $img :
$w = imagesx($this->_img);
$h = imagesy($this->_img);

$nw = 100;
$nh = 100;

$fw = $nw;
$fh = $nh;


$nh_ = ( $h * $nw )/ $w;

$fit = true;
if($fit === true ){
 if($nh_ < $nh){
  $fh = $nh;
  $fw = ( $w * $nw )/ $h;
 }else{
  $fw = $nw;
  $fh = ( $h * $nh )/ $w;
 }
}else{
 if($nh_ > $nh){
  $fw = ( $w * $nh )/ $h;
  $fh = $nh;
 }else{
  $fw = $nw;
  $fh = ( $h * $nw )/ $w;
 }
}

$tmp=imagecreatetruecolor($fw,$fh);

imagecopyresampled($tmp,$img,0,0,0,0,$fw,$fh,$w,$h);
$img = $tmp;
uset($tmp);
If we have the $fit variable set to true, then ve have this picture resized to a rectangle that can hold a 100x100 px square. If we set the $fit variable to false, we will have the image that will fit in a 100x100 px square. In both cases, the image is not yet a 100x100 px square. If we take our image, in the first case, is a rectangle with 100px height, in the seccond is a rectangle with 100px width. Now, to make it 100x100 px, we have to crop it. To do that, we center it, then crop it to the exact size:
// we recalculate the image size, because it is different now
$w = imagesx($img);
$h = imagesy($img);

// we calculate the x and y position of the point that we will use to start cropping
// so that we can fit a 100x100px square
$x = ($w - $nw)/2;
$y = ($h - $nh)/2;
After the calculations are over, we start cropping:
// we make a 100 x 100 px image
$tmp = imagecreatetruecolor($nw,$nh);
// we create a color value for the background
$clr = imagecolorallocate($tmp, 255,255,255);
// we fill the image with our background
imagefilledrectangle ($tmp, 0, 0, $nw, $nh, $clr);

// we resample the image
imagecopyresampled($tmp, $img, 0, 0, $x, $y, $nw, $nh, $nw, $nh);
$img = $tmp;

Now $img is an image resource with a 100x100 px image in it, that we can do aditional opperations, or display it.

No comments:

Post a Comment