Over a million developers have joined DZone.

Creating an Image from PixelShaders in Silverlight and WPF

DZone's Guide to

Creating an Image from PixelShaders in Silverlight and WPF

· ·
Free Resource

While this is not the best way to do image calculations in the code behind in terms of imaging with Silverlight and WPF I was perplexed with the problem of having a great pixel shader that I could apply in the xaml using Bitmap Effects but unclear as the best way to translate that to an actual Bitmap Image. If you are looking for a quick fix solution I wanted to share a little gold nugget in how to actually do this that I found. Just to explain a bit more this assumes you already know how to use Pixel Shaders, I will include a sample code to help illustrate this if you do not. But honestly that is a separate topic. I wish I had the source of this little nugget, it took alot of searching and improvising but eventually I came up with the following code:

In the XAML

    <Image x:Name="OriginalImage"  Source="img.jpg">
<l:BrightContrastEffect x:Name="MyEffect"
Brightness="{Binding ElementName=bVal, Path=Value}"
Contrast="{Binding ElementName=cVal, Path=Value}"/>

In the Code

    //using System.Windows.Media.Imaging;
//using System.Windows.Shapes;
//using System.Windows
//using System.Windows.Media;
BitmapSource bitmap = OriginalImage.Source as BitmapSource; //source from XAML
Size sz = new Size(bitmap.PixelWidth, bitmap.PixelHeight);

Rectangle r = new Rectangle();
r.Fill = new ImageBrush(bitmap);
r.Effect = MyEffect; //name applied in XAML
r.Arrange(new Rect(sz));

var rtb = new RenderTargetBitmap(
bitmap.PixelWidth, bitmap.PixelHeight,
bitmap.Dpi, bitmap.DpiY, PixelFormats.Pbgra32);

What it essentially does is takes the effect you apply in the XAML and in the back end you can use that effect to create a new bitmap. You do this by virtually constructing a rectangle of the appropriate size and shape of the original image and applying the effect and the image to the rectangle and then saving that out using RenderTargetBitmap. I will upload a sample solution when I get home this afternoon.



Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}