Created
December 21, 2022 21:17
-
-
Save mturilin/fd90c2eb50d612a54eacc38c5d4a0c02 to your computer and use it in GitHub Desktop.
F# script to compute image aspect ratio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
let resolutions = | |
[ | |
((1,1), (1080 , 1080)); | |
((3,2), (1080 , 720)); | |
((4,3), (1024 , 768)); | |
((16,9), (1920 , 1080)); | |
((16,10), (1920 , 1200)); | |
] | |
let resolutions_with_ratio = | |
resolutions | |
|> List.map (fun ((x :int, y:int),(h,v)) -> (float x/ float y, ((x,y),(h,v)))) | |
let findClosestRatio ratio = | |
resolutions_with_ratio | |
|> List.map | |
(fun (orig_ratio, data) -> | |
(abs (ratio - orig_ratio), orig_ratio, data)) | |
|> List.minBy (fun (distance, aspect, data) -> distance) | |
[<EntryPoint>] | |
let main(args) = | |
match args with | |
| [|_; resolution|] -> | |
printf $"Requested resolution is {resolution}\n" | |
match resolution.Split [|'x'|] with | |
| [|x;y|] -> | |
printf $"Comparing resolution {x} x {y} to various aspect ratios...\n" | |
match (System.Int32.TryParse x, System.Int32.TryParse y) with | |
| ((true, xInt), (true, yInt)) -> | |
let max, min = Math.Max(xInt, yInt), Math.Min(xInt, yInt) | |
let ratio = float max / float min | |
printf $"Resolution {xInt} * {yInt} has normalized ratio %0.3f{ratio}\n" | |
let distance, closest_ratio, ((x_r, y_r),(h,v)) = | |
findClosestRatio ratio | |
printf $"Closest ratio is %0.3f{closest_ratio} with distance %0.1f{distance/closest_ratio * 100.}%% \n" | |
printf $"Aspect is {x_r}:{y_r} --> Closest monitor resolution is {h}x{v}\n" | |
| _ -> failwith "The 'resolution' parameter should use the format 1234x5678" | |
| _ -> failwith "The 'resolution' parameter should use the format 1234x5678" | |
| _ -> failwith "Usage aspect_ratio <resolution>" | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment