1.场景
boss需要一个windows环境识别摄像头设备,打开设备,能够扫码并返回值的一个类库,经过一上午紧密锣鼓,搞完了。当然了,自己是不可能也不会去写基础类库的,这辈子都不可能的,只是根据需求做一定程度的业务封装使用(站在巨人的肩膀上!)
2.程序
(1)程序使用类库zxing.dll(用来识别二维码),根据图片识别二维码方法是通用的
使用Aforge.dll,Aforge.Video.dll以及Aforge.Video.DirectShow.dll 这三个动态库用来检测摄像头,启用摄像头截取画面等。
(2)具体代码如下(主要是对设备的识别处理以及得到图像)
2.2.1设立全局对象
public static Bitmap img;
FilterInfoCollection videoDevices;
VideoCaptureDevice videoCaptureDevice_on;
2.2.2获取设备mac地址:
try
{
string strMac = string.Empty;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
strMac = mo["MacAddress"].ToString();
}
}
moc = null;
mc = null;
return strMac;
}
catch(Exception ex)
{
throw ex;
}
2.2.3获取可使用摄像列表:
FilterInfo[] filterInfos;
try
{
//AForge.Video.DirectShow.FilterInfoCollection 设备枚举类
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (videoDevices.Count == 0)
throw new ApplicationException();
filterInfos = new FilterInfo[videoDevices.Count];
for (int i = 0; i < videoDevices.Count; i++)
{
filterInfos[i] = videoDevices[i];
}
}
catch (ApplicationException ex)
{
throw ex;
}
return filterInfos;
2.2.4打开任一设备(此时即可委托得到打开设备后的图片):
public void openDevice(FilterInfo device)
{
videoCaptureDevice_on = new VideoCaptureDevice(device.MonikerString);
videoCaptureDevice_on.NewFrame += new NewFrameEventHandler(video_NewFrame);
CloseVideoSource(videoCaptureDevice_on);
videoCaptureDevice_on.Start();
}
private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
img = (Bitmap)eventArgs.Frame.Clone();
}
此时,全局的img即为摄像头得到的图片(类似于动画的图片,因为是连贯的图片)(类比手机拍照,未拍照之前是连续的“动画画面”)
2.2.5使用摄像头得到的图片
在winform中做测试,建立设备列表的下拉框,增加按钮。按钮事假为开启选中的摄像头(此时已经得到全局图片变量),开启定时。
在定时器中,每隔几秒或者毫秒获取静态全局图片,放入imagebox中。(定时器间隔越小,卡顿感越弱,仿佛动画!!)
//打开选中设备,启动定时器
openDevice(videoDevices[comboBox1.SelectedIndex]);
timer2.Enabled = true;
//定时器抓取图片
private void timer2_Tick_1(object sender, EventArgs e)
{
Bitmap img = CameraReg.img;
int top = 0;
if (img == null)
{
return;
}
Bitmap img2 = (Bitmap)img.Clone();
Pen p = new Pen(Color.Red);
Graphics g = Graphics.FromImage(img2);
Point p1 = new Point(0, top);
Point p2 = new Point(pictureBox1.Width, top);
g.DrawLine(p, p1, p2);
g.Dispose();
top += 2;
top = top % pictureBox1.Height;
pictureBox1.Image = img2;
}
2.2.6 关闭摄像头设备
private void CloseVideoSource(VideoCaptureDevice videoSource)
{
if (!(videoSource == null))
if (videoSource.IsRunning)
{
videoSource.SignalToStop();
videoSource = null;
}
}
3.此时,已然得到了心心念念的图片。为所欲为了!!处理图片并识别二维码见下篇。