Skip to content
Advertisement

Show correct aspect ratio

I am trying to get the aspect ratio of a photo but the following code shows wrong aspect ratio on a photo with 3776 in width and 2520 in height (472:315) but it shows correct aspect ratio on a photo with 3968 in width and 2232 in height though (16:9).

JavaScript

How can I solve my problem?

Thanks in advance.

Advertisement

Answer

Actually, 3780×2520 is an aspect ratio of 3:2; because you’re using 3776 for the width, 472:315 is the correct ratio. If you do the division, it comes out to 1.498, which is pretty close-enough to 1.5 to consider rounding to 3:2.

If you want only “standard” ratios (like “3:2” or “16:9”), you could pass the detected ratio to another function that rounds them to find the nearest/best-match instead.

This is a thrown-together function that can do the rounding for you (only tested against the dimensions in your example, so I can’t guarantee 100% success yet):

JavaScript

To use this function, you pass in the ratio-string (not the numeric value) to it and it will attempt to “find a best match” in the common list of ratios.

Example usage:

JavaScript

The above test will output the following:

JavaScript

* I took the list of “standard” aspect ratios from wikipedia, if you want a reference.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement