Silverlight Feeds - All your Silverlight feeds in one place.

Sponsors

Monday, December 07, 2009

Creating an Image from PixelShaders in Silverlight and WPF

by Corey via Xamlmammal.com on 12/7/2009 2:00:00 PM

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">

   <Image.Effect>

      <l:BrightContrastEffect  x:Name="MyEffect"

                    Brightness="{Binding ElementName=bVal, Path=Value}"

                    Contrast="{Binding ElementName=cVal, Path=Value}"/>

  </Image.Effect>

</Image>

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.Measure(sz);

r.Arrange(new Rect(sz));

 

var rtb = new RenderTargetBitmap(

                    bitmap.PixelWidth, bitmap.PixelHeight, 

                    bitmap.Dpi, bitmap.DpiY, PixelFormats.Pbgra32);

rtb.Render(r);

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.

email it!bookmark it!digg it!

Original Post: Creating an Image from PixelShaders in Silverlight and WPF

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. Silverlight Feeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on Silverlight Feeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us