1.写在前面
上篇文章已经介绍过了ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,并对识别二维码进行了详细讲解,ZXing库不但可以识别。同样可以生成条码,而生成条码是一个经常需要使用的功能。
上一篇文章链接如下:
CSDNCSDN
https://mp.csdn.net/mp_blog/creation/editor/137614176
2.项目环境和界面搭建
项目框架:.NET Framework 4.6.1
项目依赖:ZXing.Net 在.NET Core项目中添加ZXing.NET库的引用。可以通过NuGet包管理器或手动下载并添加引用
项目界面设计:
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;
using ZXing.QrCode;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_Set_Click(object sender, EventArgs e)
{
string txt = textBox1.Text.Trim();//获取输入要转换成二维码的信息
BarcodeFormat format = BarcodeFormat.DATA_MATRIX;//更改format参数可以生成不同类型的条码
int width = 300;//设置二维码宽度和高度
int height = 300;
string filePath = "barcode.png";
GenerateBarcode(txt, format, width, height, filePath);
pictureBox1.Image = new Bitmap(filePath);//显示二维码
}
public static void GenerateBarcode(string text, BarcodeFormat format, int width, int height, string filePath)
{
var writer = new BarcodeWriter
{
Format = format,
Options = new QrCodeEncodingOptions
{
Width = width,
Height = height
}
};
var barcodeBitmap = writer.Write(text);
barcodeBitmap.Save(filePath);
}
}
}