Friday, 5 December 2014

Saving a Window or Canvas as a PNG Bitmap in WPF


The following code snippet takes a file name and a DPI value and you can chose weather to save the canvas or window to a PNG Bitmap image.

Usage:
Code Snippet
  1. Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
  2. dlg.FileName = "Image"; // Default file name
  3. dlg.DefaultExt = ".png"; // Default file extension
  4. dlg.Filter = "PNG File (.png)|*.png"; // Filter files by extension
  5.  
  6. // Show save file dialog box
  7. Nullable<bool> result = dlg.ShowDialog();
  8.  
  9. // Process save file dialog box results
  10. if (result == true)
  11. {
  12.     // Save document
  13.     string filename = dlg.FileName;
  14.     SaveCanvasToFile(this, DrawingCanvas, 96, filename);
  15. }
End of Code Snippet


Code Snippet
  1. public static void SaveCanvasToFile(Window window, Canvas canvas, int dpi, string filename)
  2. {
  3.     Size size = new Size(window.Width, window.Height);
  4.     canvas.Measure(size);
  5.     //canvas.Arrange(new Rect(size));
  6.  
  7.     var rtb = new RenderTargetBitmap(
  8.         (int)window.Width, //width
  9.         (int)window.Height, //height
  10.         dpi, //dpi x
  11.         dpi, //dpi y
  12.         PixelFormats.Pbgra32 // pixelformat
  13.         );
  14.     rtb.Render(canvas);
  15.  
  16.     SaveRTBAsPNGBMP(rtb, filename);
  17. }
  18.  
  19. public static void SaveWindowToFile(Window window, int dpi, string filename)
  20. {
  21.     var rtb = new RenderTargetBitmap(
  22.         (int)window.Width, //width
  23.         (int)window.Width, //height
  24.         dpi, //dpi x
  25.         dpi, //dpi y
  26.         PixelFormats.Pbgra32 // pixelformat
  27.         );
  28.     rtb.Render(window);
  29.  
  30.     SaveRTBAsPNGBMP(rtb, filename);
  31. }
  32.  
  33. private static void SaveRTBAsPNGBMP(RenderTargetBitmap bmp, string filename)
  34. {
  35.     var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
  36.     enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp));
  37.  
  38.     using (var stm = System.IO.File.Create(filename))
  39.     {
  40.         enc.Save(stm);
  41.     }
  42. }
End of Code Snippet

No comments: