赞
踩
一、简述
记--使用zxing条形码开源库生成条形码和识别图片中的条形码。
例子:链接: https://pan.baidu.com/s/1Xe_ZEs07mfj-YyvgApK_Zw 提取码: cy6t
zxing库下载:https://pan.baidu.com/s/10jeBSyZPvDxvPb6LXw-xlQ 提取码: xufm
官网: https://github.com/micjahn/ZXing.Net/releases
二、效果
根据输入的英文字符串生成对应的条形码,然后将条形码保存为图片,再根据图片识别出条形码的内容。
三、工程结构
四、源文件
Form1.cs文件
- 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.Common;
-
- namespace BarCode
- {
- public partial class MainForm : Form
- {
- public MainForm()
- {
- InitializeComponent();
- }
-
- //生成条形码
- private void buttonCreatorBarCode_Click(object sender, EventArgs e)
- {
- string barCodeStr = textBoxBarCodeStr.Text;
- if (barCodeStr != "")
- {
- setBarCode128(barCodeStr);
- }
- }
-
- /// <summary>
- /// 将生成的条形码设置到pictureBox
- /// </summary>
- /// <param name="acode">条形码对应的文本</param>
- public void setBarCode128(string barCodeStr)
- {
- try
- {
- EncodingOptions encodeOption = new EncodingOptions();
- encodeOption.Height = 100;
- encodeOption.Width = 300;
- ZXing.BarcodeWriter wr = new ZXing.BarcodeWriter();
- wr.Options = encodeOption;
- wr.Format = ZXing.BarcodeFormat.CODE_128;
- Bitmap img = wr.Write(barCodeStr);
- pictureBoxBarCode.Image = img;
- }
- catch
- { }
- }
-
- /// <summary>
- /// 识别条形码图片
- /// </summary>
- /// <param name="picPath">条形码图片的路径</param>
- public void getBarCode128FromPic(string picPath)
- {
- try
- {
- Bitmap img = new Bitmap(picPath);
- pictureBoxBarCodePic2.Image = img;
-
- DecodingOptions decodeOption = new DecodingOptions();
- ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
- reader.Options = decodeOption;
- ZXing.Result result = reader.Decode(img);
- string barCodeStr = result.ToString();
- labelBarCodeResult.Text = "识别结果是:"+barCodeStr;
-
- }
- catch
- { }
- }
-
- /// <summary>
- /// 打开图片文件
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void buttonOpenPicFile_Click(object sender, EventArgs e)
- {
- try
- {
- OpenFileDialog ofd = new OpenFileDialog();
- ofd.Title = "请选择条形码图片文件";//对话框的标题
- ofd.InitialDirectory = "D:\\Test";//对话框打开的目录
- ofd.Filter = "png文件|*.png|所有文件|*.*";//过滤文件类型
- DialogResult result = ofd.ShowDialog();
- string res = result.ToString();
- if (res == "OK")
- {
- string filePath = ofd.FileName;
- getBarCode128FromPic(filePath);
- }
- }
- catch { }
- }
- }
- }
五、总结
5.1 添加引用zxing库
5.2 注意
单独将生成的可执行文件(xxx.exe)放在其他目录运行或者是其它电脑运行,需要将zxing库所在路径设置到环境变量或者是将zxing.dll放在可执行文件的同级目录下。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。