This plugin for jQuery will arrange your images to fit exactly within a container. You can define the padding between images, give the images css borders and define a target row height.
CollagePlus relies on all images being loaded before it can calculate the layout. It does not run off image sizes specified in the DOM. If you have image sizes available in the DOM then you’re probably better off calculating the layout server-side (assuming that’s where you got the image sizes from) and writing the result directly to the HTML template you’re generating.