尺寸图像适合大小而不拉伸

时间:2018-02-06 15:58:30

标签: c#

我希望调整Image以适合尺寸(宽度和高度)而不拉伸原始图像。

enter image description here

我的代码,将图片大小调整为指定尺寸,但拉伸原始图像。

enter image description here

这是代码:

public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.Tile);
            graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}

1 个答案:

答案 0 :(得分:1)

因此,您希望根据宽高比进行缩放

我们应该做的是获得一个因子并根据该因素调整宽度和高度 我们不需要超出所需的宽度和高度(这就是我们在宽度和高度比率上使用Math.Min的原因)。

double oldWidth = image.Width;
double oldHeight = image.Height;

var widthRatio = width / oldWidth;
var heightRatio = height / oldHeight;

var factor = Math.Min(widthRatio, heightRatio);

在这里我们像这样使用它:

var destRect = new Rectangle(0, 0, (int)(factor * oldWidth), (int)(factor * oldHeight));
相关问题