2014-04-18 84 views
0

我有WCF服務捕捉攝像頭圖像併發送到客戶端,它在我的WinForms應用程序中效果很好。我決定創建WPF客戶端應用程序。WPF圖片來源不從流加載

我有代碼:

void timer1_Tick(object sender, EventArgs e) 
{ 
     counter++; 
     try 
     { 
      Stream imageStream = client.GetImage(); 
      using (MemoryStream stream = new MemoryStream()) 
      { 
       imageStream.CopyTo(stream); 
       int size = (int)stream.Length; 
       cam_img.Source = BitmapFrame.Create(stream, 
                BitmapCreateOptions.None, 
                BitmapCacheOption.OnLoad); 
      } 
      System.Diagnostics.Debug.WriteLine(counter); 
     } 
     catch (System.ServiceModel.CommunicationException ex) 
     { 
      if (ex.InnerException is System.ServiceModel.QuotaExceededException) 
      { 

      } 
      else 
      { 
       throw ex; 
      } 

     } 
     catch (System.Exception ex) 
     { 

     } 
} 

cam_img是圖像控制。在調試器模式中,我看到該數據流包含數據,但每個滴答事件中的cam_img.sourcenull

接下來的問題是,我必須實現propertychanged事件,使圖像動態綁定?或者在每個計時器中分配到cam_img.source刻度足以看到控制上的動態變化?

+1

什麼是'img_cam'? – terry

+0

抱歉,每個滴答事件中cam_img.source都爲null。它似乎有點不正確的bitmapfram.create,因爲流包含數據 –

+0

@ user3197850請回答問題 – csharpwinphonexaml

回答

1

問題2:

不,你需要PropertyChanged,你可以分配在每個時鐘滴答的cam_img.Source財產。 請確保你在UI線程設置cam_img.Source,否則你會得到一個InvalidOperationException說是這樣的:

,因爲不同的 線程擁有它調用線程不能訪問該對象。

問題1:

如果imageStream包含的數據,以及你喜歡的MemoryStream, 那麼你應該叫stream.Seek(0, SeekOrigin.Begin);調用BitmapFrame.Create之前移動位置回來。創建BitmapFrame

您當前的代碼將導致異常,並且異常被捕獲,所以這就是爲什麼cam_img.Source從未設置,並且仍然是默認的「空」的值。

+0

我回答,這是錯誤的,即時通訊談論cam_img.source,而不是img_cam。 –

+0

嘗試'stream.Seek(0,SeekOrigin.Begin);''我認爲這是因爲你的'stream.Position'在'imageStream.CopyTo(stream)後面的文件末尾;' – terry

+0

真的很感謝, ! –