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

gor*_*ric 6 c# silverlight bytearray bitmapimage

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

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

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

Vla*_*hov 6

用这个:

public byte[] GetBytes(BitmapImage bi)
{
    WriteableBitmap wbm = new WriteableBitmap(bi);
    return wbm.ToByteArray();
}
Run Code Online (Sandbox Code Playgroud)

哪里

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)