The problem is how to invert colors of a Silverlight Image element.
There is an Image with a JPG as a source. On a button click I need to invert the colors. Sounds simple, right. Take each pixel, then modify it’s value by 255 – pixel value. But when I tried WritableBitmap loaded with the Image source, I got security exception disallowing pixel access.
Here is my code:
if (MainLeftImage.Source != null)
{
WriteableBitmap bitmap = new WriteableBitmap((BitmapSource)MainLeftImage.Source);
byte[] pixels = new byte[bitmap.Pixels.Length];
int size = pixels.Count();
for (int i = 0; i < size; i++)
pixels[i] = (byte)(255 - pixels[i]);
bitmap.Invalidate();//redraw and then plug it back on
MainLeftImage.Source = bitmap;
}
}
catch (Exception ex)
{
}
Looks that WritableBitmap is not a solution, right?
Any help appreciated. Thanks guys.
Easiest way to invert an image would be to apply a pixel shader effect. I believe that there is an invert colors pixel shader in the WPF Pixel Shader Effects Library.
The reason that you are hitting the Security Exception is that WriteableBitmap prevents pixel access to cross-domain content. To understand why this is important, you can see my explanation of the necessity of client access policy files in this answer. To understand the point for images, just replace “secretaccountdetails.html” with “myPrivatePhoto.jpg” in the example.
If you really want to use a WriteableBitmap to access the pixels of an Image, either:
1. Make sure that the image source is served from the same domain as the application.
or
2. Make sure that the server from which the image is being served provides an appropriate client access policy and download the image file as a Stream. Use BitmapSource.SetSource(Stream) to set the source of the Image instead of setting it to the URL of the image.
In both of the above cases you will be able to access the pixels of an Image in a WriteableBitmap.