对于任何给定的最大宽度和最大高度,根据纵横比计算宽度和高度

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

我被要求将任何图片的大小调整为其等效缩略图,同时尊重图片的原始纵横比。

到目前为止,我只是在通过最高分的情况下才设法做到这一点。宽度,如下:

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);
}

我已经尝试了几种计算方法,因此它可以接受任何给定的最大值。高度和最大值宽度,以便在最终结果图片上保持原始宽高比。

此处:

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);
}

在横向模式下,您将缩略图的宽度设置为目标框的宽度,而高度是根据三的规则找到的。在纵向模式下,您将缩略图高度设置为目标框高度并计算宽度。