簡體   English   中英

將BitmapImage轉換為Byte數組

[英]Conversion of BitmapImage to Byte array

我想在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;
    }

好吧,我可以讓您的代碼變得更加簡單:

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

您能否向我們提供有關錯誤發生位置的更多信息?

我不確定你的問題到底是什么,但我知道下面的代碼是一個非常小的變化,我知道的代碼是有效的(我的是在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;
}

我有同樣的問題,這解決了它:

代號:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM