Silverlight:图像到字节[]

Spe*_*oph 6 silverlight

我能够将byte []转换为图像:

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;
Run Code Online (Sandbox Code Playgroud)

但是我无法将Image转换回byte []!我在互联网上找到了一个适用于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);
Run Code Online (Sandbox Code Playgroud)

Silverlight库非常小,以至于BitmapImage类没有名为Format的属性!

有没有人能解决我的问题.

我在互联网上搜索了很长时间才找到解决方案,但是没有解决方案,这在Silverlight中有效!

谢谢!

Chr*_*s B 7

(您丢失的每像素位方法仅详细说明每个像素如何存储颜色信息)

正如anthony建议的那样,WriteableBitmap是最简单的方法 - 请查看http://kodierer.blogspot.com/2009/11/convert-encode-and-decode-silverlight.html以获取一个获取argb字节数组的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)