Hello world. My name is Marat Isaev, I am a front-end developer for VKontakte, I develop solutions for VK Messenger. In this post, I want to talk about how to make a photo preview grid (now this option is available in VKontakte fast chats, but in the near future it will appear in the VK Messenger web version). In practice, everything is not as simple as it may seem at first glance – images come in different orientations and with different aspect ratios. Sometimes you want to focus on some images from the set, but at the same time show others.

## Popular Approach

Perhaps the most common way to create a preview grid is to describe several algorithms that will be applied to the album depending on the number of photos, their aspect ratio, and some other project-specific parameters. For example: *“If there are three photos in the album and most of them are in portrait orientation, then apply Strategy3Portrait; If there are from 5 to 10 photos, then apply Strategy5_10*». At the same time, it is important to maintain the order of the photos.

## Let’s Take It Different

I propose to consider another way to solve this problem. First of all, let’s abandon the binding to a specific number of photos and their spatial orientation. Let’s formulate the problem as follows: “*Post N photos with x sides _{n}y_{n} in a rectangle with sides AB, keeping their order*».

Then align all the photos to the height h and start laying them out like bricks.

If the photo does not fit in the current row, then move it to a new one and continue to “upload”.

Once we have finished the “masonry”, we will change the scale of each row in such a way as to fill in the “gaps”.

Now let’s check the “masonry” so that none of the pictures are too small (minimum dimensions h_{min} and w_{min}). If we are close to the aspect ratio of the rectangle a*b and the check for critical dimensions is passed, then the resulting mesh can be considered suitable.

Obviously, the better we choose h in the range from h_{min} to b, the sooner we will get the desired result. For example, you can pick up h with a binary search. Or you can do something even simpler: make several “clutches” with a delta step from h_{min} to B, and then select the option that has the closest aspect ratio to A/B.

## Algorithm Complexity

The bottleneck of this algorithm is the search for the optimal h. If we go with the delta step, the difficulty will be linear, because the number of steps is a constant. And if we search with binary search, then the difficulty will also be linear, the constant will be the range b − h_{min}, and therefore the log_{2}(b − h_{min}).

## From the world of the ideal to the real world

Is it possible to “post N photos with sides x_{n}*y _{n} in a rectangle with dimensions a*b, keeping them in order”? Yes. Is it possible to “post N photos with sides x

_{n}

*y*b, keeping their order

_{n}in a rectangle with dimensions a**and maintaining critical dimensions and original aspect ratios**»? Not always. This will depend on N, on the aspect ratio of the photos, and on a and b. In VKontakte, the number of images in the preview is limited to 10. If there is only one photo, then the grid is not needed. So, we need to somehow guarantee a good result for 2-10 images.

We are dealing with combinatorics. You need to calculate all possible options and analyze the result. And to solve the problem, we need to use “Placement with repetitions” A_{n}^{k} = n^{k} . In our case, n is the number of all possible aspect ratios of the individual photos, and k is the total number of photos (from 2 to 10). Hence the conclusion: in order for the number of placements to be finite, it is important for us that the number of possible aspect ratios is finite. For example, let’s choose five ratios: 9/16, 3/4, 1/1, 4/3, and 16/9. Then the number of placements is calculated as 5^{k} , where k = 2, …, 10. That is, if we have five photos with five possible ratios in the album, then the number of all possible options for their placement is 3125.

There is no point in describing strategies for all special cases, there are too many of them. And if we limit ourselves to squares, we can easily describe ten strategies (let me remind you that there are a number ofIn this case, there will be 1 number of placements.^{k}, k = 1, …, 10). But we want to make the preview grid as diverse as possible, so let’s think about how else we can improve the algorithm.

## Embrace the immensity. How to view and rate all grids

By defining the range of aspect ratios, we can also abandon the check for critical dimensions h_{min} and w_{min} for each individual photo, as they will become interrelated (we only need to know that the selected h ≥ h_{min} and h ≤ b). You can use a script for a set of possible placements pool __In here__.

Now let’s run the pool through our algorithm and analyze the spread of deviations in the aspect ratios of the resulting grids from the reference a/b. If the deviations are small, then fix h_{min}, a, b, and the aspect ratio values of the photos. And if the deviations are large, we correct them. It may be worth reducing the number of ratios or changing the dimensions of a and b. Often, the overall picture is spoiled by the last image, which is left alone in the last row. In such cases, you can force the last two rows to be merged.

Let’s say we need to grid photos with a 4/3 aspect ratio. Let’s assume a window width of 360 pixels and specify that the minimum height of each individual photo should be at least 80 pixels. I won’t give all the diagrams, to understand the general picture, we just need to look at the distribution of all the resulting “grids” by aspect ratio ranges for 2, 5 and 10 photos.

The more photos you have, the more room you have to maneuver. For example, if there are more than two rows and the last row contains a single image (as we discussed above), we can force the last rows to be merged.

As you can see, the more options we have, the better the mesh lends itself to post-processing. Then you can, for example, cut off too high “grids”, giving preference to those that are wider. Or vice versa, if you form grids for smartphone screens. There are many such heuristics.

If there are significantly more than 10 photos (or any other number for which you need to guarantee a result), then the selection of the best ratio can simply be omitted, as well as the selection of h, indicating it equal to h_{min}.

We will come up with a guaranteed result for any number of photos during O(n).

P.S.: If you have your own “recipe” for the preview grid, share in the comments.

———-

### Acknowledgment and Usage Notice

The editorial team at TechBurst Magazine acknowledges the invaluable contribution of Marat the author of the original article that forms the foundation of our publication. We sincerely appreciate the author’s work. All images in this publication are sourced directly from the original article, where a reference to the author’s profile is provided as well. This publication respects the author’s rights and enhances the visibility of their original work. If there are any concerns or the author wishes to discuss this matter further, we welcome an open dialogue to address potential issues and find an amicable resolution. Feel free to contact us through the ‘Contact Us’ section; the link is available in the website footer.