Find which is smaller: MaxWidth / w or MaxHeight / h
Then multiply w and h by that number
Explanation:
You need to find the scaling factor which makes the image fit.
To find the scaling factor, s, for the width, then s must be such that:
s * w = MaxWidth.
Therefore, the scaling factor is MaxWidth / w.
Similarly for height.
The one that requires the most scaling (smaller s) is the factor by which you must scale the whole image.