I have been over-thinking this complex and I am sure there is an easy answer or another avenue I can approach to find the solution.
What I am trying to accomplish is a random grid of images. I have an array of images that I want to line up in a flush grid. What I mean by this is that I want the grid to not have any gaps in it. Here are some example images:
The problem I am having is I cannot come up or put into words a formula that can create the table maxtrix I am trying to accomplish. Masonary is 99.9% what I am looking for except the grid does not take into account the image size nor does it end flush. So that 1% is why I am not considering using it.
I am not looking for javascript specific as this relates to math so I plan on creating the layout in PHP then powering functionality in javascript.
Any help or pointers will be appreciated.
Your example images are alinged in rows. Furthermore, you didn't wirte anything about a fixed total size, so I assume that the aspect ratio of the whole layout can be chosen at will. In that case, you could try something along these lines:
Obvious this is only a rough outline. The really hard part will be how to distribute the images onto the different rows. One goal might be combining images of similar aspect ratio, in such a way that the final images will have similar sizes. You could compute for each ratio the preferred image height which would lead to a desired image area, and then combine images with similar height requirements until the width resulting from scaling to a common height matches the width you desire for your final rows. But other aspects will play a role as well, e.g. making rows of similar width, and stuff like that.
You might find suggestions for objectives in other answers and comments, and toy with them until you find one you like.
Justified-Gallery looks like a solution for that, here is the site with examples.