How to calculate the proportional size for a given image so that it does not exceed

I have an area to display an image with a maximum size of 240x180

If I have a 400x423 image, how can I calculate the new width and height for this image, which works best for my 240x180? (In this case, it will be 170x180)

+3
source share
2 answers

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);
}
+5
source

Like this?

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

+1
source

Source: https://habr.com/ru/post/1788302/


All Articles