将画布保存到位图

zc2*_*c21 8 c# wpf

我想将我的画布保存到位图.我在互联网上找到了一些例子,但所有这些都只保存了黑色图像(我的画布大小).我该怎么办?

码:

    public static void SaveCanvasToFile(Canvas surface, string filename)
    {
        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.Pbgra32);
        renderBitmap.Render(surface);

        // Create a file stream for saving image
        using (FileStream outStream = new FileStream(filename, FileMode.Create))
        {               
            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);
        }}
Run Code Online (Sandbox Code Playgroud)

Ice*_*ind 10

试试这个答案:

public void ExportToPng(Uri path, Canvas surface)
{
  if (path == null) return;

  // Save current canvas transform
  Transform transform = surface.LayoutTransform;
  // reset current transform (in case it is scaled or rotated)
  surface.LayoutTransform = null;

  // Get the size of canvas
  Size size = new Size(surface.Width, surface.Height);
  // Measure and arrange the surface
  // VERY IMPORTANT
  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.Pbgra32);
  renderBitmap.Render(surface);

  // Create a file stream for saving image
  using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
  {
    // Use png encoder for our data
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    // push the rendered bitmap to it
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
    // save the data to the stream
    encoder.Save(outStream);
  }

  // Restore previously saved layout
  surface.LayoutTransform = transform;
}
Run Code Online (Sandbox Code Playgroud)

这个答案是为了方便起见从[本页]复制的.<==== LINK DEAD(http://denisvuyka.wordpress.com/2007/12/03/wpf-diagramming-saving-you-canvas-to-image -xps-document-or-raw-xaml /)

  • 这对我来说效果很好。实际上,我使用此代码创建了数百个图像,但有时此代码创建的一些图像是黑色的。可能有什么问题? (2认同)

H.B*_*.B. 0

在我的渲染代码中,我调用target.UpdateLayout();after target.Arrange(new Rect(size));,也许这会解决它。另请注意,如果未设置画布背景,它将呈现为透明,而编码为 BMP 时可能会变成纯黑色,因此如果您只有黑色对象,它们可能是不可见的。