gpt4 book ai didi

c# - 从网络摄像头输入以编程方式更新 WPF 图像控件

转载 作者:行者123 更新时间:2023-11-30 15:00:39 24 4
gpt4 key购买 nike

我正在从网络摄像头捕获图像帧,但是当我将它们设置为 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;
}
}

我的图像控件上的 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 的文档中记录了这一点.

关于c# - 从网络摄像头输入以编程方式更新 WPF 图像控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15256302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com