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
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)
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.
<DOCTYPE html>
<html>
<head>
<style>
.container {
width: 25%;
}
.container img {
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<img src="http://ldlocal.web44.net/test2/img/gallery0.jpg">
</div>
</body>
</html>