Very often during web development I needed to resize image, so it would fit in given space / dimensions aka MaxWidth / MaxHeight. Here is a little algorithm, which does a trick.
int MaxWidth = 200, MaxHeight = 400; // restrictions
int w=500, h=600; // current image dimensions
float ratio = (float)w / h;
w = MaxWidth;
h = (int)Math.Floor(MaxWidth / ratio);
if (h > MaxHeight)
{
h = MaxHeight;
w = (int)Math.Floor(MaxHeight * ratio);
}