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);
   rtb.Render(canvas);
   //endcode as PNG
   BitmapEncoder pngEncoder = new PngBitmapEncoder();
   pngEncoder.Frames.Add(BitmapFrame.Create(rtb));

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

   pngEncoder.Save(ms);
   ms.Close();
   System.IO.File.WriteAllBytes("logo.png", ms.ToArray());
   Console.WriteLine("Done");
}

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.

Enjoy!