2

I am creating an image upload form. I want to restrict users from uploading images that are not of the aspect ratio of 16:9. What is the formula for calculating an aspect ratio such as this?

If w = width, h = height, r = ratio

In other words, how is 1920:1080 formulated to an answer of 16:9?

1 Answers1

1

The requirement you specified is

$$\frac{\mathrm{width}}{\mathrm{height}} = \frac{16}9\tag 1$$

However, testing this directly in some computer program is usually a bad idea because the result of the division will be floating-point — and if it is integer, the division is not exact, either. The simplest way around it is by multiplying out $(1)$ so that all divisions disappear and the condition reads:

$$9\cdot\mathrm{width} = 16\cdot \mathrm{height} \tag 2$$

In the example of 1920:1080 = 16:9, the aspect ration fits because:

$$1920\cdot 9 = 17\,280 = 1080\cdot16$$

and the calculation only involves integers, hence there are no rounding or representation errors.


For example, in Python a function that returns True resp. False would read:

def check_aspect (width, height):
    return 9 * width == 16 * height

or in C/C++:

int check_aspect (int width, int height)
{
    return 9 * width == 16 * height;
}
emacs drives me nuts
  • 10,390
  • 2
  • 12
  • 31