3

I have an area to display an image that has a max size of 240x180

If I have an image of 400x423 how can I calculate a new width and height for that image that best fits into my 240x180 box? (In this case it would be 170x180)

Jason
  • 15,017
  • 23
  • 85
  • 116

2 Answers2

4

there are probably some image libraries that do this well, but the math is pretty simple.

ratio = orig_x * 1.0 / orig_y;

x_oversized = (orig_x > MAX_X);
y_oversized = (orig_y > MAX_Y);

if (x_oversized OR y_oversized)
{
      new_x = min(MAX_X, ratio * MAX_Y);
      new_y = min(MAX_Y, MAX_X / ratio);
}
jon_darkstar
  • 16,398
  • 7
  • 29
  • 37
1

Like this?

$newheight = 180; $newwidth = $width * $newheight / $height;