Can I get byte [] from BitmapImage in Silverlight?

I am trying to transfer some image image between Silverlight and WCF service. If possible, I would like to pass System.Windows.Media.Imaging.BitmapImage , as this would mean that the client does not need to do any transformations.

However, at some point I need to save this image in the database, that is, the image representation should be able to convert to and from byte[] . I can create a BitmapImage from byte[] by reading the array in a MemoryStream and using BitmapImage.SetSource() . But I can’t find a way to convert another path - from BitmapImage to byte[] . Did I miss something obvious here?

If this helps at all, the conversion code can be executed on the server, that is, it should not be safe for Silverlight.

+6
c # bytearray silverlight bitmapimage
source share
3 answers

Use this:

 public byte[] GetBytes(BitmapImage bi) { WriteableBitmap wbm = new WriteableBitmap(bi); return wbm.ToByteArray(); } 

Where

 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; } 
+6
source share

I had the same problem. I found the ImageTools library , which simplifies the work.

Get the library and reference it, and then

  using (var writingStream = new MemoryStream()) { var encoder = new PngEncoder { IsWritingUncompressed = false }; encoder.Encode(bitmapImageInstance, writingStream); // do something with the array } 
+1
source share

Try using CopyPixels . You can copy bitmap data into an array of bytes. However, I honestly don't know what the pixel format will be ... probably it depends on which image was originally loaded.

0
source share

All Articles