2012-04-12 29 views
0

好吧我有一個wpf圖像對象,它顯示實時圖像。所以我用一個計時器來刷新圖像。WPF成像問題

public void LoadLiveImage() 
     { 

System.Windows.Media.PixelFormat pf = PixelFormats.Bgr24; 
        int stride = 4 * ((24 * cameraFrame.img_width + 31)/32); 
        BitmapSource bmpImage= BitmapSource.Create(cameraFrame.img_width, cameraFrame.img_height, cameraFrame.img_width, cameraFrame.img_height, pf, null, cameraFrame.img_pixel, stride); 
        RemoteCameraImage.Source = bmpImage; 
} 

void dispatcherTimer_Tick(object sender, EventArgs e) 
     { 
      LoadLiveImage();   

     } 

沒有問題,這是工作正常。 但是,我試圖將其移至一個線程並且不顯示圖像。

private void showLiveImage() 
     { 
       while (this.isCameraViewOpen) 
       { 
       if (RemoteCameraImage.Dispatcher.CheckAccess()) 
         { 
          System.Windows.Media.PixelFormat pf = PixelFormats.Bgr24; 
          int stride = 4 * ((24 * cameraFrame.img_width + 31)/32); 
          BitmapSource bmpImage = BitmapSource.Create(cameraFrame.img_width, cameraFrame.img_height, cameraFrame.img_width, cameraFrame.img_height, pf, null, cameraFrame.img_pixel, stride); 
          RemoteCameraImage.Source = bmpImage; 

          System.Threading.Thread.Sleep(5); 
         } 
         else 
          this.RemoteCameraImage.Dispatcher.Invoke(DispatcherPriority.Normal, new ImageUpdater(this.showLiveImage)); 

        } 

} 

showLiveImage isrunning作爲一個線程。圖像被接收到,那裏沒有問題。我通過將img_pixel數組保存到bmp文件並生成文件來進行測試。只是圖像不顯示。所以我放了一個消息框,在源被分配後顯示,然後我能夠看到Image對象上的圖像。所以我認爲我增加了睡眠時間的問題,但即使是圖像也沒有刷新。可能是什麼問題?

編輯: 將更新圖像的代碼移動到另一個函數後,它工作正常。我用BeginInvoke()而不是調用一切正常。

回答

0

有時前,我曾similiar的問題,我發現這個#2,這sovled對我來說

Images on second thread

WPF Dispatcher {"The calling thread cannot access this object because a different thread owns it."}

如果你沒有修改圖像,一旦你有意向創建 它可以凍結它使用Freezable.Freeze,然後分配給 GeneratedImage在調度委託(BitmapImage變成 只讀y,因此Freeze會導致線程安全)。其他 選項將加載映像到後臺線程上的MemoryStream,然後在 調度程序委託與該流和BitmapImage的StreamSource屬性 在UI線程上創建BitmapImage 。

+0

問題不在於調度程序無法訪問該對象。如果我在線程中添加一些用戶操作(如MessageBox),則會顯示圖像。我也嘗試過凍結,但沒有解決問題。 – xaria 2012-04-12 09:02:43

0

嘗試使用Application.Current.Dispatcher而不是您使用的那個。 我相信這會做到這一點。

乾杯

+0

Nah ...不工作:( – xaria 2012-04-12 09:00:37