.NET MAUI(Windows)使用AForge实现摄像头预览:图像绑定问题
.NET MAUI Windows平台:用AForge Video实现摄像头预览并绑定帧到Image控件
你的核心问题需要解决两个关键点:非UI线程更新UI控件,以及将AForge的Bitmap转换为MAUI Image可识别的源,以下是具体实现方案:
关键修改步骤
- 切换到UI线程更新控件:
videoDevice_NewFrame事件在后台线程触发,MAUI的UI控件仅允许在UI线程操作,必须通过MainThread.InvokeOnMainThreadAsync切换上下文。 - Bitmap转MAUI ImageSource:将AForge返回的
System.Drawing.Bitmap通过MemoryStream转换为流,再生成StreamImageSource供Image控件使用。
修改后的MainPage.xaml.cs代码
using AForge.Video; using AForge.Video.DirectShow; using System.Drawing; using System.IO; using Microsoft.Maui.ApplicationModel; namespace TestWebCam; public partial class MainPage : ContentPage { private VideoCaptureDevice videoDevice; public MainPage() { InitializeComponent(); FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (videoDevices.Count == 0) { _ = DisplayAlert("Error", "No video devices found", "OK"); return; } videoDevice = new VideoCaptureDevice(videoDevices[0].MonikerString); videoDevice.NewFrame += videoDevice_NewFrame; videoDevice.Start(); } private async void videoDevice_NewFrame(object sender, NewFrameEventArgs eventArgs) { // 克隆帧避免原资源被提前释放 using var bitmap = (System.Drawing.Bitmap)eventArgs.Frame.Clone(); // 切换到UI线程更新Image控件 await MainThread.InvokeOnMainThreadAsync(() => { using var stream = new MemoryStream(); // 将Bitmap保存为PNG流(也可改用JPEG并调整质量参数) bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); stream.Position = 0; // 为Image控件设置数据源 myImage.Source = ImageSource.FromStream(() => stream); }); } protected override void OnDisappearing() { base.OnDisappearing(); if (videoDevice != null && videoDevice.IsRunning) { videoDevice.SignalToStop(); videoDevice.WaitForStop(); videoDevice = null; } } }
注意事项
- 内存管理:所有实现
IDisposable的对象(Bitmap、MemoryStream)都用using语句包裹,确保资源及时释放,避免内存泄漏。 - 性能优化:若预览帧率过高导致UI卡顿,可降低
VideoCaptureDevice的分辨率,或添加帧间隔采样(比如每2帧更新一次UI)。 - 权限配置:Windows平台需确保应用拥有摄像头访问权限,在
Package.appxmanifest中添加摄像头权限声明。
内容的提问来源于stack exchange,提问作者Muhammad Ibrahim
相关产品推荐
相关产品推荐

