Zxing是一个免费的条码处理软件,可生成一维码、二维码并进行读取。注释中有功能介绍
1.下载Zxing的.Net类库,并引用zxing.dll,zxing.presentation.dll
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
2.生成一维码,并保存图片
//定义变量
private int cw=200;
private int ch=200;
//定义路径
private string path=AppDomain.CurrentDomain.BaseDirectory+"\\";
private void btnCreateCode_Click(object sender,EventArgs e)
{
//设置条码的规格
EncodingOptions encoding=new EncodingOptions();
encoding.Width=cw;
encoding.Height=ch;
//生成条码的图片并保存
BarcodeWriter bw=new BarcodeWriter ();
//指定规格
bw.Options=encoding;
bw.Format=BarcodeFormat.CODE_39;
Bitmap btp=bw.Write(txtInfor.Text.Trim());
//将图片转换为字符串数组
MemoryStream ms=new MemoryStream();
btp.Save(ms,ImageFormat.Bmp);
ms.Seek(0,SeekOrigin.Begin);
byte[] buffer=new byte[ms.Length];
ms.Read(buffer,0,buffer.Length);
ms.Dispose();
using(FileStream fs=new FileStream(path+txtInfor.Text.Trim()+".bmp",FileMode.Create))
{
fs.Write(buffer,0,buffer.Length);
}
}
3.生成二维码并保存图片
private void btnCreateCode2_Click(object sender,EventArgs e)
{
//1.先设置二维码的规格
QrCodeEncodingOptions qr=new QrCodeEncodingOptions ();
//设置编码格式否则会出现乱码
qr.CharacterSet="UTF-8";
qr.Width=cw;
qr.Height=ch;
//设置二维码图片周围空白边距
qr.Margin=1;
//2.生成二维码图片并进行保存
BarcodeWriter bw=new BarcodeWriter ();
//设置为二维码
bw.Format=BarcodeFormat.QR_CODE;
//指定格式
bw.Options=qr;
Bitmap bitmap=bw.Write(txtInfor.Text.Trim());
//设置图片路径
string file=path+txtInfor.Text.Trim()+".bmp";
MemoryStream ms=new MemoryStream();
bitmap.Save(ms,ImageFormat.Bmp);
ms.Seek(0,SeekOrigin.Begin);
byte[] buffer=new byte[ms.Length];
ms.Read(buffer,0,buffer.Length);
ms.Dispose();
//保存图片
using(FileStream fs=new FileStream(file,FileMode.Create))
{
fs.Write(buffer,0,buffer.Length);
}
}
4.读取一维码
private void btnReadCode_Click(object sender,EventArgs e)
{
//1.设置读取条码的格式
DecodingOptions decoding=new DecodingOptions ();
//指定读取格式,这里的格式就是生成条码时设定的格式(两处一定要一致)
decoding.PossibleFormats=new List<BarcodeFormat>(){BarcodeFormat.CODE_39};
//2.进行读取操作
BarcodeReader br=new BarcodeReader();
//指定规格
br.Options=decoding;
Image img=null;
using(FileStream fs=new FileStream(path+txtInfor.Text.Trim()+".bmp",FileMode.Open))
{
img=Image.FromStream(fs);
}
//读取条形码
Result result=br.Decode(img as Bitmap);
}
5.读取二维码
private void btnReadCode2_Click(object sender,EventArgs e)
{
//1.设置读取二维吗规格
DecodingOptions dr=new DecodingOptions();
dr.PossibleFormats=new List<BarcodeFormat>()
{
//设置为二维码
BarcodeFormat.QR_CODE
};
//2.进行读取操作
BarcodeReader br=new BarcodeReader();
//指定规格
br.Options=dr;
Image img=null;
using(FileStream fs =new FileStream(path+txtInfor.Text.Trim()+".bmp",FileMode.Open))
{
img=Image.FromStream(fs);
}
Result rs=br.Decode(img as Bitmap);
}