计算任何给定最大宽度和最大高度的宽高度和高度

时间:2015-10-07 15:21:15

标签: c# image-resizing

我被要求将任何图片调整为等效的缩略图,同时尊重图片的原始宽高比。

到目前为止,我只是通过最大限度地完成了这项工作。宽度,如下:

public static Size GetSizeAdjustedToAspectRatio(int sourceWidth, int sourceHeight, int dWidth, int dHeight)
{
    bool isLandscape = sourceWidth > sourceHeight ? true : false;
    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);
}

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

1 个答案:

答案 0 :(得分:2)

这里:

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

在横向中,您将缩略图宽度设置为目标框宽度,并且通过规则3找到高度。在纵向中,您将缩略图高度设置为目标框高度并计算宽度。