Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Drawing;
- using System.IO;
- using System.Timers;
- using AForge.Video;
- using AForge.Video.DirectShow;
- using System.Windows.Forms;
- public class Form1 : Form
- {
- private VideoCaptureDevice videoSource;
- private int imageCounter = 0;
- private string savePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "WebCamImages");
- private Timer captureTimer;
- public Form1()
- {
- InitializeCaptureDirectory();
- InitializeVideoSource();
- InitializeTimer();
- }
- private void InitializeCaptureDirectory()
- {
- if (!Directory.Exists(savePath))
- {
- Directory.CreateDirectory(savePath);
- }
- }
- private void InitializeVideoSource()
- {
- var videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
- if (videoDevices.Count > 0)
- {
- videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
- videoSource.NewFrame += OnNewFrame;
- videoSource.Start();
- }
- }
- private void InitializeTimer()
- {
- captureTimer = new Timer(10000);
- captureTimer.Elapsed += OnTimerElapsed;
- captureTimer.Start();
- }
- private void OnNewFrame(object sender, NewFrameEventArgs eventArgs)
- {
- Bitmap image = (Bitmap)eventArgs.Frame.Clone();
- SaveImage(image);
- IncrementImageCounter();
- if (ShouldStopCapturing())
- {
- StopVideoSource();
- }
- }
- private void OnTimerElapsed(object source, ElapsedEventArgs e)
- {
- if (videoSource != null && videoSource.IsRunning)
- {
- videoSource.SignalToStop();
- videoSource.WaitForStop();
- videoSource.Start();
- }
- }
- private void SaveImage(Bitmap image)
- {
- string fileName = Path.Combine(savePath, $"Image_{imageCounter}.jpg");
- image.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
- }
- private void IncrementImageCounter()
- {
- imageCounter++;
- }
- private bool ShouldStopCapturing()
- {
- return imageCounter >= 2; // this is how many pics are taken
- }
- private void StopVideoSource()
- {
- videoSource.SignalToStop();
- videoSource.WaitForStop();
- }
- }
- public static class Module1
- {
- [STAThread]
- public static void Main()
- {
- Application.Run(new Form1());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement