neptunian
neptunian

Reputation: 410

Find the common height for 3 (or x number) images that their widths equal the set width of container element

Similar to Flickr's photo layout (https://www.flickr.com/search/?text=iceland%20westfjords) I am trying to find the common height that any given, for simplicity's sake, 3 photos in one container row would have to be in order for them to maintain their aspect ratio and fill a fixed width exactly. There is a common height that all images can grow to so that when their widths are added together equal an exact desired amount.

One easy way I achieved this was just guessing and checking in the browser. Incrementing the style height of the images using one decimal place such as 416.6px. The browser calculated the correct widths for each image without distorting them and eventually fit the width of the container (1200px).

But my problem is I have thousands of images of inconsistent aspect ratios and combinations of those in each set of 3, otherwise I'd just use css to set the height of 3 photo combinations (9 styles).

So I think what I need to do is in Javascript I need to test the 3 photos, find their aspect ratio (i have the original dimensions of each photo as data from the API), and find the common height given the clientWidth of the container row they share. I need to do this for each row (set of 3 images).

The best solution I've come up with so far is to take the original dimensions of each photo, multiple height by width to get the aspect ratio. Then guess at a common height for all the photos, say 500.5px, and divide that by each photo's aspect ratio to get the new widths of each photo. Then add the widths up to see if they total the container width, say 1200px. But this seems like I'd need to do some kind of binary search to find the common height quickly.

Can anyone think of a better algorithm that can solve directly for the common height of 3 photos, given their aspect ratios, that they would need to be in order to fill a fixed width exactly? Height has no constraints.

Thanks!

Upvotes: 0

Views: 61

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32597

Given an image of original height h and original width w, the resulting width w* for a given height h* (preserving aspect ratio) is:

w* = w/h * h*

Here, w/h is the aspect ratio of the image. Then, it's just a matter of solving the equation:

w_total = w1* + w2* + w3*
        = (aspect1 + aspect2 + aspect3) * h*

And you get the optimal height for all images:

h* = w_total / (aspect1 + aspect2 + aspect3)

Upvotes: 0

Related Questions