将BitmapImage转换为Byte数组

时间:2011-01-19 07:35:27

标签: c# windows-phone-7

我想在Windows Phone 7应用程序中将BitmapImage转换为ByteArray。所以我尝试了这个,但它抛出了运行时异常“无效的指针异常”。任何人都可以解释为什么我要做的事情抛出异常。您能为此提供替代解决方案吗?

    public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
    {
        byte[] data;
        // Get an Image Stream
        using (MemoryStream ms = new MemoryStream())
        {
            WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

            // write an image into the stream
            Extensions.SaveJpeg(btmMap, ms,
                bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

            // reset the stream pointer to the beginning
            ms.Seek(0, 0);
            //read the stream into a byte array
            data = new byte[ms.Length];
            ms.Read(data, 0, data.Length);
        }
        //data now holds the bytes of the image
        return data;
    }

3 个答案:

答案 0 :(得分:17)

好吧,我可以让你的代码变得相当简单:

public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
    using (MemoryStream ms = new MemoryStream())
    {
        WriteableBitmap btmMap = new WriteableBitmap
            (bitmapImage.PixelWidth, bitmapImage.PixelHeight);

        // write an image into the stream
        Extensions.SaveJpeg(btmMap, ms,
            bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);

        return ms.ToArray();
    }
}

......但这可能无法解决问题。

另一个问题是,您只使用bitmapImage尺寸 - 您是否应该在某个时候将其复制到btmMap

你有什么理由不只是使用它:

WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

您能否向我们提供有关错误发生位置的更多信息?

答案 1 :(得分:7)

我不确定你的问题究竟是什么,但我知道以下代码是一个非常微小的变化,我知道有效的代码(我的是在WriteableBitmap中传递,而不是BitmapImage ):

public static byte[] ConvertToBytes(this BitmapImage bitmapImage)
{
    byte[] data = null;
    using (MemoryStream stream = new MemoryStream())
    {
        WriteableBitmap wBitmap = new WriteableBitmap(bitmapImage);
        wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
        stream.Seek(0, SeekOrigin.Begin);
        data = stream.GetBuffer();
    }

    return data;
}

答案 2 :(得分:1)

我有同样的问题,这解决了它:

之前的代码:

BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bi);

以下代码:

BitmapImage bi = new BitmapImage();
bi.CreateOptions = BitmapCreateOptions.None;
bi.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bi);