C# 调整位图图像的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10839358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:29:20  来源:igfitidea点击:

Resize bitmap image

c#wpfimagebitmapresize

提问by Ionic? Biz?u

I want to have smaller size at image saved. How can I resize it? I use this code for redering the image:

我想在保存的图像时有更小的尺寸。我怎样才能调整它的大小?我使用此代码重新绘制图像:

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

采纳答案by Trevor Elliott

Does your "surface" visual have scaling capability? You can wrap it in a Viewbox if not, then render the Viewbox at the size you want.

您的“表面”视觉效果是否具有缩放功能?如果没有,您可以将其包装在 Viewbox 中,然后以您想要的大小渲染 Viewbox。

When you call Measure and Arrange on the surface, you should provide the size you want the bitmap to be.

当您在表面上调用测量和排列时,您应该提供您希望位图的大小。

To use the Viewbox, change your code to something like the following:

要使用 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);

回答by Kashif

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

回答by Breeze

The shortest way to resize a Bitmap is to pass it to a Bitmap-constructor together with the desired size(or width and height):

调整位图大小的最短方法是将其与所需的大小(或宽度和高度)一起传递给位图构造函数:

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