条码生成是一个经常需要处理的功能,本文介绍一个条码处理类库,ZXing用Java实现的多种格式的一维二维条码图像处理库,而ZXing.Net是其.Net版本的实现。
在WinForm下使用该类库需要从NuGet安装两个组件:
ZXing.Net
ZXing.Net.Bindings.Windows.Compatibility
using ZXing;
using ZXing.Common;
using ZXing.OneD;
using ZXing.QrCode;
using ZXing.Windows.Compatibility;
namespace QrCodeGen
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var writer = new BarcodeWriter<Bitmap>();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options = new QrCodeEncodingOptions()
{
DisableECI = true, //设置内容编码
CharacterSet = "UTF-8", //设置二维码的宽度和高度
Width = 200,
Height = 200,
Margin = 1 //设置二维码的边距,单位不是固定像素
};
var render = new AlternateBitmapRenderer();
writer.Renderer = render;
writer.Options = options;
Bitmap map = writer.Write("Hello world");
pictureBox1.Image = map;
}
private void button2_Click(object sender, EventArgs e)
{
var w = new EAN13Writer();
var render = new AlternateBitmapRenderer();
render.TextFont = new Font("Segoe UI", 25);
var content = "1234567890123";
// EAN-13 商品条码的标准尺寸是 37.29mm x 26.26 mm ,按照 300 DPI 换算像素大小是 440 x 310
var m = w.encode(content, BarcodeFormat.EAN_13, 440, 310);
//渲染得到的图片
var bmp = render.Render(m, BarcodeFormat.EAN_13, content, new EncodingOptions { Width = 440, Height = 310 });
pictureBox2.Image = bmp;
}
}
}
?EAN-13商品条码是表示EAN/UCC-13商品标识代码的条码符号,由左侧空白区、起始符、左侧数据符、中间分隔符、右侧数据符、校验符、终止符、右侧空白区及供人识别字符组成。