使用AForge 和 ZXing nuget 全安上了,这个还要灰度处理,代码中没有涉及
usinnugetg AForge.Video;
using AForge.Video.DirectShow;
using ZXing;
using ZXing.Windows.Compatibility;//重要,这个得引入
load
public partial class Form1 : Form
{
private static NewFrameEventHandler videoSource_NewFrame;
FilterInfoCollection videoDevices;
VideoCaptureDevice videoSource;
int selectedDeviceID = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
{
MessageBox.Show("灭有摄像头"); ;
}
else
{
foreach (FilterInfo device in videoDevices)
{
comboBox1.Items.Add(device.Name);
}
//初始化第一个
comboBox1.SelectedIndex = 0;
//videoSource.DesiredFrameSize = new Size(640, 480);
// videoSource.DesiredFrameRate = 1;
videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceID].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(NewFrameEventHandler);
videoSource.Start();
Thread.Sleep(2000);
}
void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
}
void NewFrameEventHandler(object sender, NewFrameEventArgs eventArgs)
{
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
这样 combobox里面就有摄像头了,再加上切换
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
selectedDeviceID = this.comboBox1.SelectedIndex;
//videoSource.DesiredFrameSize = new Size(640, 480);
// videoSource.DesiredFrameRate = 1;
videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceID].MonikerString);
videoSource.NewFrame += new NewFrameEventHandler(NewFrameEventHandler);
videoSource.Start();
Thread.Sleep(2000);
timer1.Enabled = true;
}
解码的代码
private void DecodeBarcode()
{
var reader = new BarcodeReader();
if (pictureBox2.Image != null)
{
var result = reader.Decode((Bitmap)pictureBox2.Image);
if (result != null)
{
System.Console.WriteLine(result);
label1.Text = result + " ";
timer1.Enabled =false;
// Invoke(new Action<Result>(ShowResult), result);
}
else
{
label1.Text = " 没事别出来";
}
pictureBox1.Image = null;
}
Thread.Sleep(200);
}