Reputation: 1941
I was asked to resize any picture to its equivalent thumbnail while respecting the original aspect ratio of the picture.
So far, I've only managed to accomplish this while only passing the max. width, like follows:
public static Size GetSizeAdjustedToAspectRatio(int sourceWidth, int sourceHeight, int dWidth, int dHeight)
{
bool isLandscape = sourceWidth > sourceHeight;
int fixedSize = dWidth;
double aspectRatio = (double)sourceWidth / (double)sourceHeight; ;
if (isLandscape)
return new Size(fixedSize, (int)((fixedSize / aspectRatio) + 0.5));
else
return new Size((int)((fixedSize * aspectRatio) + 0.5), fixedSize);
}
I've tried several ways of calculating it so that it will accept any given max. height and max. width in order to keep the original aspect ratio on the end result picture.
Upvotes: 4
Views: 4495
Reputation: 3344
Here:
public static Size GetSizeAdjustedToAspectRatio(int sourceWidth, int sourceHeight, int dWidth, int dHeight) {
bool isLandscape = sourceWidth > sourceHeight;
int newHeight;
int newWidth;
if (isLandscape) {
newHeight = dWidth * sourceHeight / sourceWidth;
newWidth = dWidth;
}
else {
newWidth = dHeight * sourceWidth / sourceHeight;
newHeight = dHeight;
}
return new Size(newWidth, newHeight);
}
In landscape, you set the thumbnail width to the destination box width and height is found by rule of three. In portrait, you set the thumbnail height to the destination box height and calculate width.
Upvotes: 5