调整位图图像大小

11

我希望保存的图片尺寸更小。如何调整大小?我使用以下代码渲染图片:

Size size = new Size(surface.Width, surface.Height);
surface.Measure(size);
surface.Arrange(new Rect(size));
// Create a render bitmap and push the surface to it
RenderTargetBitmap renderBitmap =
    new RenderTargetBitmap(
        (int)size.Width,
        (int)size.Height, 96d, 96d,
        PixelFormats.Default);
renderBitmap.Render(surface);

BmpBitmapEncoder encoder = new BmpBitmapEncoder();
// push the rendered bitmap to it
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
// save the data to the stream
encoder.Save(outStream);
3个回答

35
public static Bitmap ResizeImage(Bitmap imgToResize, Size size)
{
    try
    {
        Bitmap b = new Bitmap(size.Width, size.Height);
        using (Graphics g = Graphics.FromImage((Image)b))
        {
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
        }
        return b;
    }
    catch 
    { 
        Console.WriteLine("Bitmap could not be resized");
        return imgToResize; 
    }
}

1
没有try-catch块,这是完美的。 - Chris Shouts
“Size” 部分很重要,我发现多个旧答案使用了 2 个整数,但现在你需要一个大小。感谢您注意到这一点,节省了一些麻烦。(为了让未来的观众知道使用 2 个整数的答案需要相应更改而进行评论) - Max von Hippel

9

将Bitmap传递给Bitmap构造函数并与所需的大小(或宽度和高度)一起使用是调整Bitmap大小的最简单方法:

bitmap = new Bitmap(bitmap, width, height);

对我有用。给你点赞以弥补某些人的不礼貌行为。 - srking
完美运行。 - theMohammedA
3
这种解决方案的缺点是默认缩放是为了速度而优化的,而不是为了质量。根据被缩放的对象(以及缩放到的大小),这可能会导致锯齿状和其他图形伪影。 Kashif 的解决方案允许选择缩放插值算法。 - Russell Bearden

3

你的“surface”视觉元素是否具备缩放功能?如果没有,你可以将其包装在Viewbox中,然后以所需大小呈现Viewbox。

当你调用surface上的Measure和Arrange时,应提供位图所需的大小。

要使用Viewbox,请将你的代码更改为以下内容:

Viewbox viewbox = new Viewbox();
Size desiredSize = new Size(surface.Width / 2, surface.Height / 2);

viewbox.Child = surface;
viewbox.Measure(desiredSize);
viewbox.Arrange(new Rect(desiredSize));

RenderTargetBitmap renderBitmap =
    new RenderTargetBitmap(
    (int)desiredSize.Width,
    (int)desiredSize.Height, 96d, 96d,
    PixelFormats.Default);
renderBitmap.Render(viewbox);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接