调整位图图像的大小

时间:2012-05-31 18:41:21

标签: c# wpf image bitmap resize

我希望保存较小的图像尺寸。 我怎样才能调整它? 我使用此代码来重新映射图像:

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 个答案:

答案 0 :(得分:33)

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 :(得分:6)

调整位图大小的最短方法是将其与所需的size(或width and height)一起传递给Bitmap构造函数:

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

答案 2 :(得分:3)

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

当您在曲面上调用Measure and 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);