【问题标题】:Update WPF Image Control Programmatically from Webcam Input从网络摄像头输入以编程方式更新 WPF 图像控件
【发布时间】:2013-03-06 19:30:21
【问题描述】:

我正在从网络摄像头捕获图像帧,但是当我将它们设置为 WPF 的图像控件时,它显示为空白。

我正在使用的库返回一个 Bitmap,因此我将其转换为 BitmapImage,然后通过 Dispatcher 将 Image 控件的源设置为 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;
        }
    }

我的 Image 控件上的 XAML 声明尽可能通用:

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

Image 控件中没有显示任何内容 - 没有运行时错误。我做错了什么?
非常感谢您的帮助!

【问题讨论】:

    标签: c# wpf webcam


    【解决方案1】:

    您需要在创建 BitmapImage 时设置bi.CacheOption = BitmapCacheOption.OnLoad。没有它,位图会被延迟加载,并且当 UI 开始请求它时,流将被关闭。 Microsoft 在BitmapImage.CacheOption 的文档中对此进行了说明。

    【讨论】:

      【解决方案2】:

      除了将图像写入临时 MemoryStream 之外,您还可以通过调用 Imaging.CreateBitmapSourceFromHBitmap 直接从 Bitmap 转换为 BitmapSource:

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

      【讨论】:

        猜你喜欢
        • 2011-10-15
        • 2020-07-06
        • 1970-01-01
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2012-03-31
        • 2014-06-18
        相关资源
        最近更新 更多