繁体   English   中英

从网络摄像头输入以编程方式更新WPF图像控制

[英]Update WPF Image Control Programmatically from Webcam Input

我正在从网络摄像头捕获图像帧但是当我将它们设置为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控件中没有显示任何内容 - 没有运行时错误。 我究竟做错了什么?
非常感谢你的帮助!

在创建BitmapImage时,需要设置bi.CacheOption = BitmapCacheOption.OnLoad 如果没有这个,就会懒惰地加载位图,并且在UI到达时要求它关闭流。 Microsoft在BitmapImage.CacheOption的文档中注意到了这一点。

您可以通过调用Imaging.CreateBitmapSourceFromHBitmap直接从Bitmap转换为BitmapSource ,而不是将图像写入临时MemoryStream:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM