WPF中的大图像更新被延迟进行实时监控

时间:2017-06-06 12:46:17

标签: c# wpf bitmap type-conversion imagesource

我从USB获取图像序列并抓取每个图像我将抓取的结果转换为System.Drawing.Bitmap然后我将其转换为System.Windows.Mesia.Imging.BitmapImage以便能够将其分配给Imagesource最后在调度程序线程中更新UI,所有这些过程都需要时间并且它不会生效,相机公司(Basler)的示例代码使用了C#并直接将System.Drawing.Bitmap分配给图片框并且可以显示现场观点毫不拖延。 处理它的最佳解决方案是什么?值得一提的是,对于2048 * 2000像素大小,帧速率几乎为50 fps

PixelDataConverter converter = new PixelDataConverter();
            Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
            BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            converter.OutputPixelFormat = PixelType.BGRA8packed;
            IntPtr ptrBmp = bmpData.Scan0;
            converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult); 
            bitmap.UnlockBits(bmpData);

            BitmapImage bitmapimage = new BitmapImage();
            using (MemoryStream memory = new MemoryStream())
            {
                bitmap.Save(memory, ImageFormat.Bmp);
                memory.Position = 0;
                bitmapimage.BeginInit();
                bitmapimage.StreamSource = memory;
                bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapimage.EndInit();
                bitmapimage.Freeze();
            }
            Dispatcher.Invoke(new Action(() =>
            {
                imgMain.Source = bitmapimage;
            }));

这是c#公司的示例代码:

Bitmap bitmap = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format32bppRgb);
                    // Lock the bits of the bitmap.
                    BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
                    // Place the pointer to the buffer of the bitmap.
                    converter.OutputPixelFormat = PixelType.BGRA8packed;
                    IntPtr ptrBmp = bmpData.Scan0;
                    converter.Convert(ptrBmp, bmpData.Stride * bitmap.Height, grabResult); //Exception handling TODO
                    bitmap.UnlockBits(bmpData);

                    // Assign a temporary variable to dispose the bitmap after assigning the new bitmap to the display control.
                    Bitmap bitmapOld = pictureBox.Image as Bitmap;
                    // Provide the display control with the new bitmap. This action automatically updates the display.
                    pictureBox.Image = bitmap;
                    if (bitmapOld != null)
                    {
                        // Dispose the bitmap.
                        bitmapOld.Dispose();
                    }
                }
enter code here

1 个答案:

答案 0 :(得分:1)

使用Dispatcher.BeginInvoke代替Dispatcher.Invoke(...将图片设置为异步。

       Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
       {
             imgMain.Source = bitmapimage;
       }));