C#使用Zxing.dll组件解析二维码
1.首先下载Zxing.dll组件,将dll组件放置debug文件夹中,引用参考,引入空间命名。
2.解码方法
- string result = string.Empty;
- //--解码
- private string RQDecode(Bitmap img)
- {
- string errText = string.Empty;
- Result result = null;
- if (img != null)
- {
- try
- {
- result = new BarcodeReader().Decode(new Bitmap(pictureBox1.Image));
- string barCodeStr = result.ToString();
- labelBarCodeResult.Text = "识别结果是:" + barCodeStr;
- //listBox1.Items.Add(barCodeStr);
- }
- catch { return errText; }
- if (result != null)
- {
- return result.Text;
- }
- else
- {
- return errText;
- }
- }
- else
- {
- return errText;
- }
- }
3.全部源码
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using ZXing;
-
-
- namespace Code_test
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private string pathname = string.Empty;//定义路径名变量
- private void button1_Click(object sender, EventArgs e)
- {
- DialogOperate openfile = new DialogOperate();//实例化对象
- textBox1.Text = openfile.OpenFile();//调用方法,显示图片路径
- pathname = textBox1.Text;//获取文件路径
- if (pathname != string.Empty)//这个判断用处不大
- {
- try
- {
- this.pictureBox1.Load(pathname);//加载图片路径
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- }
-
- }
-
- string result = string.Empty;
- //--解码
- private string RQDecode(Bitmap img)
- {
- string errText = string.Empty;
- Result result = null;
- if (img != null)
- {
- try
- {
- result = new BarcodeReader().Decode(new Bitmap(pictureBox1.Image));
- string barCodeStr = result.ToString();
- labelBarCodeResult.Text = "识别结果是:" + barCodeStr;
- //listBox1.Items.Add(barCodeStr);
- }
- catch { return errText; }
- if (result != null)
- {
- return result.Text;
- }
- else
- {
- return errText;
- }
- }
- else
- {
- return errText;
- }
- }
-
- private void button2_Click(object sender, EventArgs e)
- {
- RQDecode(new Bitmap(pictureBox1.Image));//开始解析
- }
- }
- }
4.效果图