【问题标题】:WPF imaging problemsWPF 图像问题
【发布时间】:2012-04-12 17:21:45
【问题描述】:

好的,我有一个 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 作为线程运行。图像被接收,这没有问题。我通过将 img_pixel 数组保存到 bmp 文件进行了测试,并生成了文件。只是图像不显示。因此,我在分配源后放置了一个要显示的消息框,然后我就可以在 Image 对象上看到图像。所以我认为我增加了睡眠时间的问题,但即使图像没有刷新。可能是什么问题?

编辑: 将更新图像的代码移动到另一个函数后,它工作正常。我使用 BeginInvoke() 而不是调用一切正常。

【问题讨论】:

    标签: wpf multithreading image


    【解决方案1】:

    前段时间我遇到了类似的问题,我在 Stackoverflow 上找到了这个,它为我解决了这个问题

    Images on second thread

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

    如果您不打算在创建后修改图像 您可以使用 Freezable.Freeze 将其冻结,然后分配给 调度程序委托中的 GeneratedImage(BitmapImage 变为 只读,因此由于冻结是线程安全的)。另一个 选项是将图像加载到 MemoryStream 上 后台线程,然后在 UI 线程上创建 BitmapImage 具有该流和 StreamSource 属性的调度程序委托 位图图像。

    【讨论】:

    • 问题不在于调度程序无法访问该对象。如果我在线程中添加一些用户操作,比如 MessageBox,图像就会显示出来。我也尝试了冻结,它没有解决问题。
    【解决方案2】:

    尝试使用 Application.Current.Dispatcher 而不是您使用的那个。 我相信这会成功。

    干杯

    【讨论】:

      猜你喜欢
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      相关资源
      最近更新 更多