配置环境:VS2012+Zxing0.14.0.0
Zxing链接地址:https://download.csdn.net/download/kissgoodbye2012/10275837
一、一维码生成(barcode)
// 1.设置条形码规格
EncodingOptions encodeOption = new EncodingOptions();
encodeOption.Height = 130; // 必须制定高度、宽度
encodeOption.Width = 240;
// 2.生成条形码图片并保存
ZXing.BarcodeWriter wr = new BarcodeWriter();
wr.Options = encodeOption;
wr.Format = BarcodeFormat.EAN_13; // 条形码规格:EAN13规格:12(无校验位)或13位数字
Bitmap img = wr.Write(this.ContentTxt.Text); // 生成图片
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\EAN_13-" + this.ContentTxt.Text + ".jpg";
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
// 3.读取保存的图片
this.ImgPathTxt.Text = filePath;
this.barCodeImg.Image = img;
MessageBox.Show("保存成功:" + filePath);
EncodingOptions包含在using ZXing.Common;
ContentTxt为一个输入文本框。
这个一维码代码将文本框的输入信息转换为一维码。
条形码中有很多码制,这里是EAN13。对我的应用来说,掌握一种就够了,反正是自己定义,自己识别。
只能生成数字的一维码图片。不能是汉字和字母。
二、条形码的识别
// 1.设置读取条形码规格
DecodingOptions decodeOption = new DecodingOptions();
decodeOption.PossibleFormats = new List<BarcodeFormat>() {
BarcodeFormat.EAN_13,
};
// 2.进行读取操作
ZXing.BarcodeReader br = new BarcodeReader();
br.Options = decodeOption;
ZXing.Result rs = br.Decode(this.barCodeImg.Image as Bitmap);
if (rs == null)
{
this.ContentTxt.Text = "读取失败";
MessageBox.Show("读取失败");
}
else
{
this.ContentTxt.Text = rs.Text;
MessageBox.Show("读取成功,内容:" + rs.Text);
}
DecodingOptions包含在using ZXing.Common;
对于怎么得到一维码在图片中的位置,后续再探索。(err)
三、二维码的生成(Qrcode)
扫描二维码关注公众号,回复:
3624102 查看本文章
// 1.设置QR二维码的规格
ZXing.QrCode.QrCodeEncodingOptions qrEncodeOption = new ZXing.QrCode.QrCodeEncodingOptions();
qrEncodeOption.CharacterSet = "UTF-8"; // 设置编码格式,否则读取'中文'乱码
qrEncodeOption.Height = 200;
qrEncodeOption.Width = 200;
qrEncodeOption.Margin = 1; // 设置周围空白边距
// 2.生成条形码图片并保存
ZXing.BarcodeWriter wr = new BarcodeWriter();
wr.Format = BarcodeFormat.QR_CODE; // 二维码
wr.Options = qrEncodeOption;
Bitmap img = wr.Write(this.ContentTxt.Text);
string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\QR-" + this.ContentTxt.Text + ".jpg";
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
// 3.读取保存的图片
this.ImgPathTxt.Text = filePath;
this.barCodeImg.Image = img;
MessageBox.Show("保存成功:" + filePath);
QrCodeEncodingOptions包含于ZXing.QrCode
四、二维码的识别
// 1.设置读取二维码规格
DecodingOptions decodeOption = new DecodingOptions();
decodeOption.PossibleFormats = new List<BarcodeFormat>() {
BarcodeFormat.QR_CODE,
};
// 2.进行读取操作
ZXing.BarcodeReader br = new BarcodeReader();
br.Options = decodeOption;
ZXing.Result rs = br.Decode(this.barCodeImg.Image as Bitmap);
if (rs == null)
{
this.ContentTxt.Text = "读取失败";
MessageBox.Show("读取失败");
}
else
{
this.ContentTxt.Text = rs.Text;
MessageBox.Show("读取成功,内容:" + rs.Text);
}
五、获取二维码位置
ZXing.Result rs = br.Decode(this.barCodeImg.Image as Bitmap);
textBox1.Text = rs.ResultPoints.GetValue(0).ToString();
textBox2.Text = rs.ResultPoints.GetValue(1).ToString();
textBox3.Text = rs.ResultPoints.GetValue(2).ToString();
textBox1等为输入框的显示;
三个得到的是二维码上三个点。