Conversion of BitmapImage to Byte array

2019-01-08 00:22发布

I want to convert a BitmapImage to ByteArray in a Windows Phone 7 Application. So I tried this but it throws the runtime Exception "Invalid Pointer Exception". Can anyone explain why what I'm trying to do throws an exception. And can you provide an alternative solution for this.

    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条回答
女痞
2楼-- · 2019-01-08 01:06

Well I can make the code you've got considerably simpler:

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

... but that probably won't solve the problem.

Another issue is that you're only ever using the size of bitmapImage - shouldn't you be copying that onto btmMap at some point?

Is there any reason you're not just using this:

WriteableBitmap btmMap = new WriteableBitmap(bitmapImage);

Can you give us more information about where the error occurs?

查看更多
看我几分像从前
3楼-- · 2019-01-08 01:07

I had same problem, this solves it:

Code before:

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

Code after:

BitmapImage bi = new BitmapImage();
bi.CreateOptions = BitmapCreateOptions.None;
bi.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bi);
查看更多
祖国的老花朵
4楼-- · 2019-01-08 01:22

I'm not sure exactly what your problem is, but I know that the following code is a very minor change from code that I know works (mine was passing in a WriteableBitmap, not a 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;
}
查看更多
登录 后发表回答