An easy problem, but for some reason I just can't figure this out today.
I need to resize an image to the maximum possible size that will fit in a bounding box while maintaining the aspect ratio.
Basicly I'm looking for the code to fill in this function:
void CalcNewDimensions(ref int w, ref int h, int MaxWidth, int MaxHeight);
Where w & h are the original height and width (in) and the new height and width (out) and MaxWidth and MaxHeight define the bounding box that the image must fit in.
Best Answer
Find which is smaller:
MaxWidth / w
orMaxHeight / h
Then multiplyw
andh
by that numberExplanation:
You need to find the scaling factor which makes the image fit.
To find the scaling factor,
s
, for the width, thens
must be such that:s * w = MaxWidth
. Therefore, the scaling factor isMaxWidth / w
.Similarly for height.
The one that requires the most scaling (smaller
s
) is the factor by which you must scale the whole image.