Brief Explanation
I am currently building a gallery that has three columns, each column contains images all of which have the same width, but can vary in height.
The images for the columns are gathered from a directory and placed into an array using the PHP glob()
function. This is the easy part...
An example of what the gallery looks like:
The Issue
As these images are being loaded and placed into the columns dynamically, there is a chance that the columns may differ in height hugely.
For instance, if two portrait photos were placed in column 1, and two landscape photos were placed in column 2, the columns would be very uneven like so:
It is extremely unlikely that the columns will ever match in height, but I would like them to be as close as possible with the given images and therefore would like to form an algorithm that will look at the images retrieved and place them in the columns to return three columns that are as close in height as they can be.
So, for example, the script would correct the above problem by re-sorting the images and placing them like so:
I am capable of writing this if I have the correct algorithm, I just cannot think of the best steps to do this. Can anyone suggest any steps?
Possible Solution
One of the methods I thought of (I think there will be better ways as I think this is flawed):
- Add up the height of all of the images combined and divide by the number of columns (3). This will give us the height to aim for
- Distribute the images to the column array and when it exceeds the height of the column, overflow onto the next column.
- Place any left over images into the first column, then second column etc...
Thanks in advance
You can try somethig like this. Create array:
Add image to column with the smallest $totalHeigth and increase height of that column with added image height.
So if in some loop you have array like this:
you will know that image need to be added in column 2.
I'd suggest something along the following:
Hope this helps!