我可以从Silverlight中的一个BitmapImage的一个byte []? [英] Can I get a byte[] from a BitmapImage in Silverlight?

查看:194
本文介绍了我可以从Silverlight中的一个BitmapImage的一个byte []?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to pass some representation of an image back and forth between Silverlight and a WCF service. If possible I'd like to pass a System.Windows.Media.Imaging.BitmapImage, since that would mean the client doesn't have to do any conversion.

然而,在某些时候,我需要这个图像存储在数据库中,这意味着图像表示必须能够转换和从字节[] 。我可以创建一个的BitmapImage 字节[] 通过读取阵列成 MemoryStream的,并使用 BitmapImage.SetSource()。但我似乎无法找到一种方法,另一种方式转换 - 从的BitmapImage 字节[] 。我失去了一些东西明显在这里?

However, at some point I need to store this image in a database, meaning the image representation must be able to convert to and from byte[]. I can create a BitmapImage from a byte[] by reading the array into a MemoryStream and using BitmapImage.SetSource(). But I can't seem to find a way to convert the other way - from BitmapImage to byte[]. Am I missing something obvious here?

如果它有助于在所有的转换代码可以在服务器上运行,也就是说,它并不需要是Silverlight的安全。

If it helps at all, the conversion code could run on the server, i.e. it doesn't need to be Silverlight-safe.

推荐答案

使用这样的:

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

这篇关于我可以从Silverlight中的一个BitmapImage的一个byte []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆