This article explains the use of an ASP.NET handler to serve up images using WPF and XAML templates to manipulate images. The results are incredible, and not comparable with any commercial component.
Remember: the root element of the XAML page must be a "
WPF works in an STA thread, ASP.NET in an MTA, and this is a limit.
Using the code
The handler works on IIS 6. On IIS 7, I have some problems rendering the 3D objects (I'm working on it).
To use the handler, you need to call "Xaml.ashx", passing some mandatory parameters:
xaml: name on the XAML file without extension
enc: the encoder; available options: PNG, JPG, TIF, BMP, WMP, GIF
As an example URL: "xaml.ashx?w=500&h=300&xaml=xamlshield&enc=png".
By modifying the handler, you can also pass the image name via URL (look for the commented code).
How it works
There are three stages on the handler:
- Set the thread and start it.
- Load the XAML file with a XAML reader.
- Capture the rendered output, encode it, and send it.
The first stage is in the sub
Dim thread As System.Threading.Thread = _
New System.Threading.ThreadStart(AddressOf GimmeMore))
thread.IsBackground = True
I'm setting the thread
ApartmentState to STA and starting it.
The second stage is in the sub
Dim sr As New System.IO.StreamReader(_
CurrentContext.Request.PhysicalApplicationPath + XamlDoc + ".xaml")
Dim xaml As String = sr.ReadToEnd()
Dim ms As New System.IO.MemoryStream(xaml.Length)
Dim sw As New System.IO.StreamWriter(ms)
Dim parserContext As New ParserContext()
parserContext.BaseUri = New Uri(CurrentContext.Request.PhysicalApplicationPath)
MyImage = CType(System.Windows.Markup.XamlReader.Load(ms, parserContext), _
CurrentContext.Request.PhysicalApplicationPath + "sunset.jpg"))
Dim slt As PageDelegate
slt = New PageDelegate(AddressOf Capture)
I load the XAML file and call, with
Dispatcher.Invoke, the capture sub.
Note: I commented some code, you can use it to dynamically assign the image to the XAML file (in the examples, use the file xamlshield.xaml).
In the last stage (sub
Capture()), I capture the rendered output with the prefered encoder.
Why do I use
Dispatcher.Invoke? It is the only tested method to capture the binding in the rendered XAML.
On IIS 7, the handler works, but only the Viewport3D is not rendered (no 3D effects). Searching for a solution....
History and Credits
- Marco Zhou, MSFT and MSDN forum moderator.
- Cristian Civera, MVP.