我正在创建wpf应用程序并在我的项目中实现一个网络摄像头。下面是我如何尝试从usb网络摄像头捕获图像。
public partial class CameraWindow : Window
{
VideoCaptureDevice LocalWebCam;
public FilterInfoCollection LocalWebCamsCollection;
private BitmapImage latestFrame;
Action<BitmapImage> captureImage;
void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
try
{
System.Drawing.Image img = (Bitmap)eventArgs.Frame.Clone();
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
bi.Freeze();
this.latestFrame = bi;
Dispatcher.BeginInvoke(new ThreadStart(delegate
{
previewWindow.Source = bi;
}));
}
catch (Exception ex)
{
}
}
public CameraWindow(Window window)
{
this.Owner = window;
InitializeComponent();
Loaded += CameraWindow_Loaded;
Unloaded += CameraWindow_Unloaded;
}
private void CameraWindow_Loaded(object sender, RoutedEventArgs e)
{
LocalWebCamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
LocalWebCam = new VideoCaptureDevice(LocalWebCamsCollection[0].MonikerString);
LocalWebCam.VideoResolution = LocalWebCam.VideoCapabilities[0];
LocalWebCam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
LocalWebCam.Start();
}
private void CameraWindow_Unloaded(object sender, RoutedEventArgs e)
{
LocalWebCam.Stop();
}
private void manualCapture_Click(object sender, RoutedEventArgs e)
{
if (captureImage != null)
{
captureImage(latestFrame);
}
}
}
XAML:
<Grid>
<!--<ComboBox x:Name="camListCb" Margin="10,25,10,415" Height="26"></ComboBox>-->
<Image x:Name="previewWindow" Margin="10,10,10,40"></Image>
<Button x:Name="manualCapture" Height="26" Width="40" Content="CAP" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="5" Click="manualCapture_Click"></Button>
<Label x:Name="testLabelAsd" Content="" HorizontalAlignment="Left" Margin="80,438,0,0" VerticalAlignment="Top"/>
</Grid>
我接下来要做的是将捕获的图像保存到c:\tmp并显示捕获图像的标签数量。如何做到这一点?有什么帮助吗?
1条答案
按热度按时间ccrfmcuu1#
通过将
BitmapImage
转换为Bitmap
解决了保存捕获图像的问题:然后将
BitmapImageToBitmap
方法添加到manualCapture_Click
。