How to Save XAML as an Image

Here’s a quick note to self that you may enjoy. I suck at art. Didn’t use to always, but it requires too much brain power. But I’m not bad at getting WPF to draw what I want. I had a logo in mind for this site and used WPF to generate it after unsuccessfully getting Paint.NET to do the same.

I recently needed to use this code again, but forgot how I solved it. So, rather than hunt it down on Google again, I came home and loaded up ye olde Windows Live Writer to write this post.

To save the XAML you want as an image, put the elements you want to save into a canvas element called canvas. Then run the following code.

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
   Rect rect = new Rect(canvas.RenderSize);
   RenderTargetBitmap rtb = new RenderTargetBitmap((int)rect.Right,
     (int)rect.Bottom, 96d, 96d, System.Windows.Media.PixelFormats.Default);
   //endcode as PNG
   BitmapEncoder pngEncoder = new PngBitmapEncoder();

   //save to memory stream
   System.IO.MemoryStream ms = new System.IO.MemoryStream();

   System.IO.File.WriteAllBytes("logo.png", ms.ToArray());

I hooked up a key binding to a command to execute this code, but you could use a button click too. It’ll save the elements in canvas to a file in the same folder as the executable, called logo.png, but you can change that if you want. You can also you a different encoder if you like. They’re in System.Windows.Media.Imaging.


3 Replies to “How to Save XAML as an Image”

  1. Something that I’ve been struggling with in dealing with XAML-to-Image conversion code is positioning. If your canvas is positioned inside of a parent container in any way, you have to take that into account or else your canvas will be cut-off in the resulting image.

    For example, if your canvas is inside of a grid (as mine was), the first line needs to look more like:

    Rect rect = new Rect(canvas.Margin.Left, canvas.Margin.Top, canvas.ActualWidth, canvas.ActualHeight);

  2. I noticed something similar when I tried this again. The Window and Canvas had to be similar sizes or the image would be empty.

Comments are closed.