Calculating Shader Effects in WriteableBitmap (Fast Float Computations And More)
Jan 11, 2010
Here's a small code snippet that allows you to calculate any pixel shader and get the output into a WriteableBitmap!
Stream stream = Application.GetResourceStream(new Uri("SilverlightApplication1;component/Images/test.jpg", UriKind.Relative)).Stream;
WriteableBitmap result = new WriteableBitmap(1, 1); // avoid creating intermediate BitmapImage
Image image = new Image();
image.Effect = new BlurEffect(); // any pixel shader effect
image.Source = result; // set the image to the original
result.Invalidate(); // render the pixel shader
image.Source = null; // release the bitmap reference
image.Effect = null;
GC.Collect(); // remove all obsolete bitmaps from memory [optional]
// result contains the image with shader effect applied! assign it to any Image.Source!
myImage.Source = result;
For the sample, I used InvertColorEffect() that I had on my PC, but you could try with your own (or just use the BlurEffect() to see how it works).
Note that the image doesn't even have to be part of the UI tree, and you don't have to wait for a render pass!
Why is this good?
In an apples-to-apples comparison (float computations) pixel shaders are much faster than managed code. See http://kodierer.blogspot.com/2009/08/silverlight-3-writeablebitmap.html for performance comparison. This means that you can now run even faster computations from managed code in Silverlight!
Also in case Silverlight eventually executes shaders on the GPU (I don't know what is the plan about that), your applications will really be able to benefit from the fast computations!
There is also one other reason why is it so good: but I'll mention it in a later post (working on secret project now...) :)