I have managed to fit automatically the images of the gallery per row depending if it´s horizontal (one image per row) or vertical (two images per row).
use percentages for the container containing the image (for both it's width and height).. then also use percentage for the image's width and height as well (it doesn't have to be 100%, it just has to be a percentage relative to its container)