Export Silverlight Visuals to Images

In a couple of my previous Silverlight projects I would have liked to export what a user saw on screen to an image that they could keep on their local machine. My last project involved creating diagrams and it would have been great to allow them to save them locally or to email them without having to fire up Silverlight. While this functionality is available in WPF, it was sadly missing from the Silverlight 2.0 platform. I had seen a number of proposed solutions such as loading your XAML in WPF at the server and rendering it there, none of which were tempting.

One of the new features in Silverlight 3.0 is a WriteableBitmap class. This is similar to it’s big brother in WPF and allows a developer to both render a visual to a bitmap and also be able to access it’s Pixel data. Great huh? Unfortunately although Silverlight 3.0 lets you render Visuals to a Bitmap and get at it’s pixel data, there is no easy way to save that Image locally.

I imagine the primary reason Microsoft introduced the WriteableBitmap in Silverlight 3.0 is so we can generate images dynamically and mess with it’s pixel data. Some of the clever bods in our community (Joe Stegman and Ian Griffiths) had already managed to achieve this functionality in Silverlight 2.0 by dynamically rendering a Png to a stream and getting Silverlight to display that. So if they can render a bunch of pixels to a Png, what’s stopping us from just rendering that to a file? As it turns out, nothing.

Using the Silverlight 3.0 WriteableBitmap I’m able to grab a Silverlight visual and render it to a Bitmap. Once I have the bitmap I can just take it’s Pixel data and run it through the PngGenerator created by Joe. With the rendered Png data we can ask the user where they would like to save the image and write it out to the resulting stream. I’ve rolled up this up into a single PngRenderer class so now you can simply pass it the element you would like to render and the stream you would like to render it to. Easy stuff.

var saveDialog = new SaveFileDialog
    {
        Filter = "Png Flies (*.png)|*.png"
    };

var result = saveDialog.ShowDialog();

if (result ?? false)
{
    using (var stream = saveDialog.OpenFile())
        PngRenderer.RenderElementToStream(MyPanel, stream);
}

This is an example rendering produced by this code. If you have Silverlight 3.0 why not take a look at a live sample.

SilverlightRender

This works and enables you to export an Image of a Silverlight visual locally to the user. So great huh? Unfortunately it kind of sucks, the Png that we’re writing is uncompressed so for even a moderately sized image it can easily reach file sizes of over a megabyte. Ideally we would write a compressed Png but as Silverlight doesn’t provide this functionality natively we would have to write it ourselves, I haven’t done this yet. If anyone feels like writing a managed Png encoder or knows one that already exists please let me know!

You can download the PngRenderer class and Joe’s PngGenerator class which it requires here.

Advertisements

Silverlight JavaScript Value Converter

Value converters allow you to modify the value of the source property of a binding before it is applied to the target. As shown in my previous WPF examples, you would normally write a new class implementing the IValueConverter interface which will do the conversion. For simple transforms such as performing basic arithmetic or formatting a string writing a whole new class can feel like overkill. In WPF a nice way of doing simple transformations on bindings is to use the EvalBinding but unfortunately, there is not a version for Silverlight and due to the lack of Markup Extensions it is difficult to create anything similar.

This became a particular problem in a recent Silverlight project where we were using loose XAML to enable different themes per client for portions of the application and could not know all the possible conversion required in advance. I wanted to be able to use some kind of scripting to express how the binding’s value should be modified and to have this all expressed in XAML. I’ve recently seen a few folks using IronPython scripts inside their .NET applications to enable scripting at runtime and I’ve also used Boo in the past to achieve similar functionality. Both of these options would involve bundling their respective libraries to the client which when we’re writing a consumer facing Silverlight application – the extra weight doesn’t seem very attractive.

Of course why bother including a whole new scripting language in your Silverlight application when you’ve already got one? Silverlight applications are more than likely run from inside a browser which can already run JavaScript. Using this we can create a Value Converter which will use a JavaScript function to perform the transformation in the binding.

<TextBlock>
    <TextBlock.Text>
        <Binding Source="{StaticResource Message}" Converter="{StaticResource ScriptConverter}">
            <Binding.ConverterParameter>
                <sys:String>
                    var t = '';
                    for (var i = 0; i &lt; value.length; i++) {
                        t += value.charAt(value.length - 1 - i);
                    }
                    return t;
                </sys:String>
            </Binding.ConverterParameter>
        </Binding>
    </TextBlock.Text>
</TextBlock>

This example will take convert the bound value, "foobar", and run the javascript specified passing in the value of the Binding as the variable named ‘value’. For readers not familiar with Javascript the example will reverse the text, so that "foobar" becomes "raboof" when displayed in the TextBlock. The syntax is a little strange to look at. Because we’re specifying the script we have to use the full definition of the Binding instead of the common inline attribute syntax. Silverlight does not support CData sections so any invalid characters in XML such as the less than comparison in the for statement has to be escaped.

Calling out to the browser to execute the supplied function is surprisingly easy; we simply create the method and invoke it with the value. The body of the ValueConverter only contains 5 lines of code.

public class ScriptValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Format a JSON definition with the converter body making up the function
        var json = "( { 'convert': function(value) { " + parameter.ToString() + "} } )";
        // Create the javascript object
        var o = (ScriptObject)HtmlPage.Window.Eval(json);
        // Get a reference to the Javascript conversion function
        var convertFunction = (ScriptObject)o.GetProperty("convert");
        // Invoke the function with the value to convert from
        var convertedValue = convertFunction.InvokeSelf(value);

        return convertedValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
} 

ScriptValueConverter

I should point out that I haven’t given much thought to performance or security in this example, before using Javascript for your conversions you should think thoroughly about where the script is coming from and how often it will be updated. There is also no error handling so a badly written conversion function will likely tear down your entire application.

Download a sample project here.