Save canvas to bitmap

前端 未结 6 471
感动是毒
感动是毒 2020-12-06 02:32

I want to save my canvas to bitmap. I found some examples in internet, but all of those saves only black image (with size of my canvas). What can I do with this?

Co

6条回答
  •  悲哀的现实
    2020-12-06 03:12

    Try this answer:

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

    This answer was copied here for convenience from [this page.]<====LINK DEAD(http://denisvuyka.wordpress.com/2007/12/03/wpf-diagramming-saving-you-canvas-to-image-xps-document-or-raw-xaml/)

提交回复
热议问题