- Hướng dẫn đọc webcam trong Windows Form C# bằng thư viện Aforge
- Chụp ảnh màn hình bằng C#
Để đọc webcam trong Windows Form C# thì phương pháp sử dụng thư viện Aforge là nhanh chóng, dễ dàng và hoàn toàn miễn phí. Bài viết này hướng dẫn chi tiết cách tích hợp vào Windows Form sử dụng .NET framework.
Bài viết này nằm trong seri khóa học C# từ căn bản đến nâng cao
Mục lục
Tích hợp thư viện
Sau khi tạo project Windows Form .NET framework 4.7.2 sử dụng ngôn ngữ C#, các bạn cần reference 2 file DLL sau:
- AForge.Video.DirectShow.dll
- AForge.Video.dll
Sau đó các bạn tạo 1 combobox cb_webcam để hiển thị danh sách webcam:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
void LoadWebcam() { cb_webcam.Items.Clear(); FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice); if (videosources.Count == 0) return; for (int i = 0; i < videosources.Count; i++) { cb_webcam.Items.Add(videosources[i].Name); } cb_webcam.Enabled = true; if (cb_webcam.Items.Count == 1) { cb_webcam.SelectedIndex = 0; } } |
Và tạo 1 combobox để load resolution của webcam đó
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
void LoadResolution() { if (cb_webcam.Items.Count == 0) return; FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice); VideoCaptureDevice videoSource = new VideoCaptureDevice(videosources[cb_webcam.SelectedIndex].MonikerString); cb_resolution.Items.Clear(); foreach (var cap in videoSource.VideoCapabilities) { cb_resolution.Items.Add(cap.FrameSize.Width + "x" + cap.FrameSize.Height); } if (cb_resolution.Items.Count > 0) { cb_resolution.SelectedIndex = 0; } } |
Start webcam và hiển thị
Bạn cần tạo 1 picture tên là picWebcam để hiển thị bitmap
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
void StartWebcam() { if (cb_webcam.Items.Count == 0 || cb_webcam.SelectedIndex == -1) return; if (m_videoSource != null) { m_videoSource.Stop(); } FilterInfoCollection videosources = new FilterInfoCollection(FilterCategory.VideoInputDevice); m_videoSource = new VideoCaptureDevice(videosources[cb_webcam.SelectedIndex].MonikerString); m_videoSource.VideoResolution = selectResolution(m_videoSource, cb_resolution.SelectedIndex); m_videoSource.NewFrame += new NewFrameEventHandler(OnCameraFrame); m_videoSource.Start(); } void OnCameraFrame(object sender, NewFrameEventArgs eventArgs) { picWebcam.Image = new Bitmap(eventArgs.Frame); } |
Link GitHub
https://github.com/thigiacmaytinh/TGMTcs/tree/main/3.3_WebcamAforge