views:

479

answers:

2

I need to resize images in php using GD to a fixed size but maintain the orientation (portrait/landscape), these are:

portrait: 375 x 500px landscape: 500 x 375px

Everything I have tried always ignores the orientation and makes them all landscape.

Can anyone help?

+2  A: 

Check the width and height of the incoming image. If the width is wider than the height, make your target size 500 x 375, otherwise make it 375 x 500. Then run the resize code with those target dimensions.

Scott Saunders
And since you already have an gd image resource you can use imagesx() and imagesy() to get the width and height.
VolkerK
+1  A: 

Here is a method from an image class I use that calculates the scaled dimensions of an image. It works by fitting an image into a square box.

You can set $box = 500 and then pass the $x and $y of the image you are trying to resize and it will always return the correct resized dimensions maintaining the aspect ratio.

public static function fit_box($box = 200, $x = 100, $y = 100)
{
  $scale = min($box / $x, $box / $y, 1);
  return array(round($x * $scale, 0), round($y * $scale, 0));
}
Giles Smith
Hm, the question is not about scaling but how to determine whether an image has portrait (height>=width) or landscape (width>=height) orientation.
VolkerK
I assumed that he wanted to maintain the aspect ratio as well as the orientation whilst resizing the images, which is what my function will do. The function will always keep the larger dimension at 500px whilst matching the shorter dimension without needing to know the orientation.
Giles Smith