Silverlight: image in bytes []

I can convert byte [] to image:

byte[] myByteArray = ...; // ByteArray to be converted MemoryStream ms = new MemoryStream(my); BitmapImage bi = new BitmapImage(); bi.SetSource(ms); Image img = new Image(); img.Source = bi; 

But I can’t convert the image back to byte []! I found on the Internet a solution that works for WPF:

 var bmp = img.Source as BitmapImage; int height = bmp.PixelHeight; int width = bmp.PixelWidth; int stride = width * ((bmp.Format.BitsPerPixel + 7) / 8); byte[] bits = new byte[height * stride]; bmp.CopyPixels(bits, stride, 0); 

The Silverlight library is so small that the BitmapImage class does not have a property called Format!

Is there an idea that solves my problem.

I searched the Internet for a long time to find a solution, but there is no solution that works in silverlight!

Thanks!

+6
silverlight
source share
3 answers

(a bit per pixel method that you are missing just details how color information is stored per pixel)

As Anthony suggested, WriteableBitmap would be the easiest way - see http://kodierer.blogspot.com/2009/11/convert-encode-and-decode-silverlight.html for the argb byte array method:

 public static byte[] ToByteArray(this WriteableBitmap bmp) { // Init buffer int w = bmp.PixelWidth; int h = bmp.PixelHeight; int[] p = bmp.Pixels; int len = p.Length; byte[] result = new byte[4 * w * h]; // Copy pixels to buffer for (int i = 0, j = 0; i < len; i++, j += 4) { int color = p[i]; result[j + 0] = (byte)(color >> 24); // A result[j + 1] = (byte)(color >> 16); // R result[j + 2] = (byte)(color >> 8); // G result[j + 3] = (byte)(color); // B } return result; } 
+7
source share

There is no solution that works in Silverlight by design. Images can be extracted without having to comply with any cross-domain access policy, as other HTTP requests require. The basis of this relaxation of cross-domain rules is that the data making up the image cannot be retrieved. It can only be used as an image.

If you want to just write and read from a bitmap, use the WriteableBitmap class instead of BitmapImage . WriteableBitmap provides a Pixels property not available in BitmapImage .

+3
source share
  public static void Save(this BitmapSource bitmapSource, Stream stream) { var writeableBitmap = new WriteableBitmap(bitmapSource); for (int i = 0; i < writeableBitmap.Pixels.Length; i++) { int pixel = writeableBitmap.Pixels[i]; byte[] bytes = BitConverter.GetBytes(pixel); Array.Reverse(bytes); stream.Write(bytes, 0, bytes.Length); } } public static void Load(this BitmapSource bitmapSource, byte[] bytes) { using (var stream = new MemoryStream(bytes)) { bitmapSource.SetSource(stream); } } public static void Load(this BitmapSource bitmapSource, Stream stream) { bitmapSource.SetSource(stream); } 
+2
source share

All Articles