I cannot come up with idiomatic Mathematica code to solve this simple problem:

1. take: image and desired aspect ratio
1. get image dimensions
2. upsize the dimensions to desired aspect ratio
2. return{{left, right}, {bottom, up}} for ImagePad

https://www.instagram.com/p/CMxh05OH4Ss/ (⬅️ needed the answer for these)

• for (1) you can use ImageAspectRatio
– kglr
Mar 23 at 22:48
• @kglr I know but I am struggling to get the second argument to ImagePad calculated o__O Mar 23 at 23:02

I have come up with this:

pad // ClearAll
pad[d_, r_] := Module[{n, w, h},
n = Max[d]/Max[r]*Min[r];
{w, h} = Clip[(n - d)/2, {0, \[Infinity]}];
{w, h} {{1, 1}, {1, 1}} // Round
]


To answer the request for an example photo:

i = "https://i.stack.imgur.com/3GmI2.png" // Import
r = {4, 5} (* {w, h} = instagram portrait aspect ratio *)

• do you mind adding an example input(s) showing the connection to image aspect ratio?
– kglr
Mar 24 at 0:07
ClearAll[pad2]
pad2[i_Image, ar_] := Module[{d = ImageDimensions @ i},
Round[{#, #}/2] & /@ Ramp[Max[d] Min[ar, 1/ar] - d]] ImagePad[#, pad2[#, 4/5], "Fixed"] & @ ImageRotate[i, Pi/2] • This does feel more idiomatic! Sweet use of Ramp and 4/5. Obviously, I was not posting the above receipt to Instagram but (helping post) a watercolor painting by my wife 💖: instagram.com/p/CMxh05OH4Ss Mar 24 at 11:42
• @CetinSert, wonderful pictures!
– kglr
Mar 24 at 11:57

Would the following do?

pad[im_Image, r : {w_, h_}] :=
Module[{idim = ImageDimensions[im],
ratim = Divide @@ ImageDimensions[im], rat = Divide @@ r, pad},
If[ratim < rat
, pad = Round[ (idim[] rat - idim[])/2];

• I guess so (not a fan of the explicit If though, feels too C-ish) but I also believe something a lot shorter than both of our answers must be possible with a language like Mathematica. Mar 24 at 11:13