上次的二维码项目中,在解析的时候用的是扫码枪自动解析并以键盘形式输出,二次开发及通用性不高。本次项目使用AForge库调用摄像头采集二维码照片,再使用ZXing库解析二维码,较之前通用性更高。
一、调用摄像头
1.首先安装AForge库
2.在工具箱中将视频组件添加到winfrom界面界面中
3.代码如下所示,增加了一个comobox摄像头列表来加载不同的摄像头。
public partial class Form1 : Form
{
FilterInfoCollection videoDevices;//摄像头设备集合
VideoCaptureDevice videoSource;//捕获设备源
const int delaytime = 500; //扫码间隔时间 ms
int totalTime; //扫码最长时间
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1_Click(null, null);
}
// 获取视频输入设备
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);//获取拍照设备列表
for (int i = 0; i < videoDevices.Count; i++)
comboBox1.Items.Add(videoDevices[i].Name);
comboBox1.Text = comboBox1.Items[0].ToString();
}
// 开始识读
private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.Text == null)
return;
ShutCamera();
videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);
videoSourcePlayer1.VideoSource = videoSource;
videoSourcePlayer1.Start();
textBox1.Text = "开始识读";
timer1.Interval = delaytime;
timer1.Start();
totalTime = 0;
}
// 停止识读
private void button3_Click(object sender, EventArgs e)
{
ShutCamera();
timer1.Stop();
}
// 关闭并释放摄像头
public void ShutCamera()
{
if (videoSourcePlayer1.VideoSource != null)
{
videoSourcePlayer1.SignalToStop();
videoSourcePlayer1.WaitForStop();
videoSourcePlayer1.VideoSource = null;
}
}
}
二、解析二维码
为了方便快捷,二维码解析依然使用ZXing库提供的解析函数。主要的想法是新建一个timer,在timer中利用摄像头每隔一段时间采集一张图片,将图片导入到ZXing解析函数中,如果识别成功就停止timer。代码如下:
private void timer1_Tick(object sender, EventArgs e)
{
if (totalTime >= 20000)// 最多读20秒
{
timer1.Stop();
ShutCamera();
textBox1.Text = "未识别到二维码";
return;
}
Bitmap picture;
picture = videoSourcePlayer1.GetCurrentVideoFrame();//拍摄
if (picture != null)
{
// 识读QR码
BarcodeReader reader = new BarcodeReader();
reader.Options.CharacterSet = "UTF-8";
Result resultQR = reader.Decode(picture);
if (resultQR != null)
{
textBox1.Text = "QR码:\r\n";
string[] strList = resultQR.Text.Split(',');
for (int i = 0; i < strList.Length; i++)
textBox1.AppendText(i.ToString("d2") + ":" + strList[i] + "\r\n");
timer1.Stop();
ShutCamera();
return;
}
}
totalTime += delaytime;
textBox1.Text = totalTime.ToString() + " ms";
//if (totalTime == 3000)
// picture.Save("测试图片.bmp");
}