6

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

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

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

4

3 回答 3

6

用这个:

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;
}
于 2010-12-03T10:58:50.017 回答
1

我遇到过同样的问题。我发现ImageTools 库可以让工作更轻松。

获取库并引用它,然后

                        using (var writingStream = new MemoryStream())
                        {
                            var encoder = new PngEncoder
                            {
                                IsWritingUncompressed = false
                            };
                            encoder.Encode(bitmapImageInstance, writingStream);
                            // do something with the array
                        }
于 2011-02-14T10:01:13.553 回答
0

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

于 2009-12-05T03:04:29.713 回答