Home » Android » android – Getting the aspect ratio of any video-Exceptionshub

# android – Getting the aspect ratio of any video-Exceptionshub

Questions:

I want to get the aspect ratio of nay video in android like (1:1, 9:16 etc). Currently i get the height and width of a video but i want the aspect ratio. Is this task is possible with Ffmpeg or MediaMetadataRetriever? If yes, then please give me some example code. If no, then please suggest me the other solutions.

The aspect ratio is just the ratio of the height to the width* – as you can get those I think what you are looking for is simply a way to reduce them to the lowest ratio.

This is a common maths exercise – you divide each number by their greatest common divisor, which is the largest number which will divide into both numbers (https://en.wikipedia.org/wiki/Greatest_common_divisor).

There is a nice example in Java using a recursive modulus division here you can use: https://stackoverflow.com/a/4009247/334402

So in summary you:

• get the height and width (e.g. 1500, 500)
• get their greatest common divisor, gcd (500 in this example)
• dived the gcd into both numbers and get your aspect ratio is its lowest terms (3:1 in this example)

(*) Update. Actually @llogan’s very good answer includes both SAR and DAR aspect ratios. Sample Aspect ratio, SAR, is the original source aspect ratio and Display Aspect Ratio is the aspect ration of the video as it is intended to be displayed. There is a third term you may see sometimes also, Pixel aspect ratio which is the DAR divided by the SAR. I suspect it is still the DAR you are interested in so the height and width approach you used still applies.

# ffprobe

``````\$ ffprobe -loglevel error -show_entries stream=sample_aspect_ratio,display_aspect_ratio -of default=nw=1 input.mkv
sample_aspect_ratio=115:87
display_aspect_ratio=1840:783
``````

This will provide both the SAR and DAR.

# mediainfo

``````\$ mediainfo --Output="Video;%DisplayAspectRatio%,%DisplayAspectRatio/String%,%PixelAspectRatio%,%DisplayAspectRatio_Original%,%DisplayAspectRatio_Original/String%" input.mkv
2.350,2.35:1,1.322,1.778,16:9
``````

As shown in this example there are many aspect ratios to choose from and they can be displayed in several forms, such as 16:9 or 1.778.

For more info see `mediainfo --Help-Output` and `mediainfo --Info-Parameters`.