2013-05-18 60 views
2

我試圖從服務返回的字節數組中創建BitmapImage從字節數組創建BitmapImage

我的代碼是:

using (sc = new ServiceClient()) 
{ 
    using (MemoryStream ms = new MemoryStream(sc.GetImage())) 
    { 
     Display = new BitmapImage(); 
     Display.BeginInit(); 
     Display.StreamSource = ms; 
     Display.EndInit(); 
    } 
} 

然而,一個例外是在EndInit方法拋出。它說Object reference not set to an instance of an object.

看來,Uri是空的,它會導致問題。不幸的是,我自己找不到解決方案。

+0

按照[文件](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.streamsource.aspx),你還可以指派一個值到'Display.UriSource'?如果是這樣,它會忽略'StreamSource'。另外,你有'CacheOption'屬性設置爲'BitmapCacheOption.OnLoad'嗎?編輯:此外,它似乎是'顯示'是一個成員(字段/屬性),是否有可能你有一個線程問題在這裏取代/更改'顯示'當你使用它? –

+0

@ChrisSinclair,我沒有分配給UriSource一個優點。我只是檢查了一個堆棧跟蹤,在我看來,由於這個屬性而拋出了一個空指針異常。這只是一個猜測。顯示器確實是一個屬性,它綁定到我的XAML佈局。所以,基本上我想從WCF服務獲取圖像,然後在WPF窗口中顯示它。除此綁定外,我沒有可能導致線程問題的代碼。 –

+0

你可以嘗試將'CacheOption'屬性設置爲'BitmapCacheOption.OnLoad'嗎?否則,從我所瞭解的情況來看,它將懶洋洋地嘗試訪問可能在讀取它時關閉的流。根據評論[這裏](http://stackoverflow.com/a/2250851/1269654)一定要在'BeginInit()'之後設置它。編輯:即:'Display = new BitmapImage(); Display.BeginInit(); Display.CacheMode = BitmapCacheOption.OnLoad; Display.StreamSource = ms; Display.EndInit();' –

回答

4

那麼,事實證明,WPF綁定導致了錯誤。

private BitmapImage _display; 
public BitmapImage Display 
{ 
    get { return _display; } 
    set 
    { 
     _display = value; 
     RaisePropertyChanged("Display"); 
    } 
} 

我解決了這個問題,通過獲取圖像不在屬性顯示本身,而是在提交_display。所以,以下工作正常。

using (sc = new ServiceClient()) 
{ 
    using (MemoryStream ms = new MemoryStream(sc.GetImage())) 
    { 
     _display = new BitmapImage(); 
     _display.BeginInit(); 
     _display.CacheOption = BitmapCacheOption.OnLoad; 
     _display.StreamSource = ms; 
     _display.EndInit(); 
    } 
} 

Display = _display; 
1

u正在將memory stream直接分配給bitmapsource,這會導致error。 首先你需要得到那arraybytes &比convert它進入memory stream然後分配給bitmap source,就是這樣!

using (sc = new ServiceClient()) 
    { 
      Byte[] array = sc.GetImage(); 

      Display = new BitmapImage(); 
      Display.BeginInit(); 
      Display.StreamSource = new MemoryStream(array); 
      Display.EndInit(); 
    } 
+1

我不知道你可以在'byte []'上使用';我認爲它必須是「IDisposable」。編輯:快速測試,我不認爲你可以。這段代碼(假設你修復它)與提供的代碼有什麼不同?它只是避免處理流? –

+0

答案已經更新。 –

+0

更新後的答案中的描述是_exactly_德米特里已經在做什麼。你的答案和他的原始代碼之間的唯一區別在於你的答案不會處理內存流。 –