简体   繁体   中英

Calculate Width and Height respecting Aspect Ratio for any given Max Width and Max Height

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM