我可以从Silverlight中的BitmapImage获取byte 吗?

我试图在Silverlight和WCF服务之间来回传递一些图像。 如果可能的话,我想传递一个System.Windows.Media.Imaging.BitmapImage ,因为这意味着客户端不必进行任何转换。

但是,在某些时候我需要将此图像存储在数据库中,这意味着图像表示必须能够转换为byte[]和从byte[]转换。 我可以通过将数组读入MemoryStream并使用BitmapImage.SetSource()byte[]创建BitmapImage 。 但我似乎无法找到另一种方式转换 – 从BitmapImagebyte[] 。 我错过了一些明显的东西吗?

如果它有帮助,转换代码可以在服务器上运行,即它不需要是Silverlight安全的。

用这个:

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

哪里

 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; } 

我遇到过同样的问题。 我找到了ImageTools库 ,使得工作更轻松。

获取库并引用它然后

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

尝试使用CopyPixels 。 您可以将位图数据复制到字节数组。 但是,老实说我不确定像素的格式是什么……它可能取决于最初加载的图像类型。