How to Export a Graph to a Bitmap Image

Tips & Tricks

Summary

This article shows how the contents of a CanvasControl (e.g. a graph) can be exported to a bitmap image in yFiles for Silverlight.

Description

Since neither Silverlight 3, 4, or 5, nor yFiles for Silverlight provide a built-in encoder for image formats like PNG or JPG, a third party library needs to be used for actually encoding bitmap data into an image that can be saved to a stream and opened later on by other softwares.

We found the .NET Image Tools to be a versatile and convenient library that is available under the Microsoft Public License (Ms-PL) to work well in that scenario.

yFiles for Silverlight 2.0 and higher support integration of bitmap encoders out of the box. Please refer to the yFiles for Silverlight Developer's Guide for further information.
For the actual image format encoding, third party libraries are still required.

The following example code (yFiles for Silverlight before version 2.0) exports the current contents of the graph control to a PNG file on the disk. The code should be used in response to a button press, because Silverlight requires user interaction to open up a file save dialog.

ContextConfigurator cc = new ContextConfigurator(graphControl.Viewport, graphControl.Zoom);
Transform transform;
Geometry clip;
IRenderContext renderContext = cc.Setup(graphControl, out transform, out clip);
FrameworkElement content = graphControl.CreateVisualContent(renderContext);


double w = graphControl.GetContentHost().ActualWidth;
double h = graphControl.GetContentHost().ActualHeight;

WriteableBitmap bitmap = new WriteableBitmap((int) w, (int) h);


content.Measure(new Size(w, h));
content.Arrange(new Rect(0, 0, w, h));

// help Silverlight to get on its knees - bindings are not resolved unless the content becomes "visible"
var popup = new Popup(){
    Child = new Canvas(){Clip = Geometry.Empty, Children = {content}}, 
    IsOpen = true, Visibility = Visibility.Collapsed};

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Image Files (*.png)|*.png";
if (sfd.ShowDialog() == true) {
  // we need to do this later, otherwise bindings have not yet affected the rendering...
  Dispatcher.BeginInvoke(delegate {
    // this call needs to be done later...
    bitmap.Render(content, transform); 
    Image myImage = bitmap.ToImage();
    using (Stream stream = sfd.OpenFile()) {
      var encoder = new PngEncoder();
      encoder.Encode(myImage, stream);
      stream.Close();
    }
  });
}

Categories this article belongs to:
yFiles for Silverlight > yFiles for Silverlight Viewer > Input and Output
Applies to:
yFiles for Silverlight: 1.0, 1.0.1, 2.0, 2.1, 2.2, 2.3
Keywords:
PNG - JPEG - JPG - GIF - BMP - image - export - bitmap - save - saving - WriteableBitmap - ContextConfigurator - encoder - encoding