2011-01-19 131 views
13

我想在Windows Phone 7應用程序中將BitmapImage轉換爲ByteArray。所以我嘗試了這一點,但它引發了運行時異常「無效的指針異常」。任何人都可以解釋爲什麼我想要做什麼拋出異常。你能爲此提供一個替代解決方案嗎?將BitmapImage轉換爲字節數組

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

回答

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

你能不能給我們介紹一下發生錯誤的更多信息?

+0

事實上,我已經使用上述的事情,WriteableBitmap的btmMap =新WriteableBitmap的(的BitmapImage);以前我已經展示了錯誤的東西。但仍顯示相同的錯誤「無效的指針」。 – dinesh 2011-01-19 08:03:11

+2

當我嘗試使用你的方法時,除非我使用構造函數中的BitmapImage將btmMap初始化爲一個WritableBitmap,否則就會變黑。我不確定我是否缺少某種設置,但我想我會提到它。 – 2012-01-19 22:53:45

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