2013-03-06 59 views
3

我從網絡攝像頭捕獲圖像幀,但是當我將它們設置爲WPF的圖像控件時,它顯示爲空白。從網絡攝像頭以編程方式更新WPF圖像控件輸入

我使用返回位圖的庫,所以我將它轉換爲BitmapImage的,然後將我的形象控制到BitmapImage的通過調度來源:

void OnImageCaptured(Touchless.Vision.Contracts.IFrameSource frameSource, Touchless.Vision.Contracts.Frame frame, double fps) 
    { 
     image = frame.Image; // This is a class variable of type System.Drawing.Bitmap 
     Dispatcher.Invoke(new Action(UpdatePicture)); 
    } 

    private void UpdatePicture() 
    { 
     imageControl.Source = null; 
     imageControl.Source = BitmapToBitmapImage(image); 
    } 

    private BitmapImage BitmapToBitmapImage(Bitmap bitmap) 
    { 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      bitmap.Save(ms, ImageFormat.Png); 
      ms.Position = 0; 
      BitmapImage bi = new BitmapImage(); 
      bi.BeginInit(); 
      bi.StreamSource = ms; 
      bi.EndInit(); 
      return bi; 
     } 
    } 

我的圖像控制的XAML聲明是關於儘可能通用:

<Image x:Name="imageControl" HorizontalAlignment="Left" Height="100" Margin="94,50,0,0" VerticalAlignment="Top" Width="100"/> 

Image控件中沒有顯示任何內容 - 沒有運行時錯誤。我究竟做錯了什麼?
非常感謝您的幫助!

回答

3

當您創建BitmapImage時,您需要設置bi.CacheOption = BitmapCacheOption.OnLoad。如果沒有這樣的話,位圖會被延遲加載,並且在用戶界面得到請求時流將被關閉。 Microsoft在BitmapImage.CacheOption的文檔中註明了這一點。

+1

這個工作。非常感謝你! – 2013-03-06 19:51:04

2

相反圖像寫入到一個臨時的MemoryStream你也可以直接致電Imaging.CreateBitmapSourceFromHBitmapBitmap轉換爲BitmapSource的:

private void UpdatePicture() 
{ 
    imageControl.Source = Imaging.CreateBitmapSourceFromHBitmap(
     image.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, 
     BitmapSizeOptions.FromEmptyOptions()); 
} 
+0

太棒了。這也適用。 – 2013-03-06 20:28:33

+0

而且代碼少得多...... – Clemens 2013-03-06 20:32:06