将BitmapImage转换为Byte数组

din*_*esh 13 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;
    }
Run Code Online (Sandbox Code Playgroud)

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

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

另一个问题是,你永远只能用大小bitmapImage-你不应该被复制到这btmMap在某些时候?

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

WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);
Run Code Online (Sandbox Code Playgroud)

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

  • @LeoNguyễn:我还没有尝试过,但您是否尝试过创建一个`BitmapImage`然后将`StreamSource`设置为包含字节数组的`MemoryStream`? (3认同)
  • 当我尝试使用你的方法时,我最终得到一个黑色图像,除非我使用构造函数中的BitmapImage将btmMap初始化为WritableBitmap.我不确定我是否缺少某种设置,但我想我会提到它. (2认同)

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