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).
The problem now
This would be better to solve with CSS. Just set the img width to 100% and it will expand contract with the size of its parent. In the example below .container takes up 25% of the window and the img takes up 100% of that. You can use firebug to change the width of the container and see the difference.