ZXing.NET 生成Datamatrix二维码

公司与第三方公司合作进行数据对接要使用二维码进行数据读取,考虑可能存在的数据不少于是想用Datamatrix二维码

什么是Datamatrix?

Datamatrix是二维码的一个成员,于1989年由美国国际资料公司发明,广泛用于商品的防伪、统筹标识。

Datamatrix是一种矩阵式二维条码,其发展的构想是希望在较小的条码标签上存入更多的资料量。Datamatrix的最小尺寸是所有条码中最小的,尤其特别适用于小零件的标识,以及直接印刷在实体上。说白了就是为了装更多数据

直接上代码:


using System.Drawing;
using System.Drawing.Imaging;
using ZXing;
using ZXing.Datamatrix;
using ZXing.Windows.Compatibility;

Console.WriteLine("Hello, World!");

Console.WriteLine("请输入要生成 DataMatrix 二维码的内容:");
string content = Console.ReadLine() ?? string.Empty;

if (string.IsNullOrWhiteSpace(content))
{
	Console.WriteLine("内容不能为空!");
	return;
}
string filePath = string.Empty;
try
{
	// 生成 DataMatrix 二维码
	var writer = new BarcodeWriterPixelData
	{
		Format = BarcodeFormat.DATA_MATRIX,
		Options = new DatamatrixEncodingOptions
		{
			Width = 300,
			Height = 300,
			Margin = 1,
			PureBarcode = true,
			CharacterSet = "UTF-8" // 新增,指定 UTF-8 编码
		}
	};

	var pixelData = writer.Write(content);

	// 创建 Bitmap 并保存为 PNG
	using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppRgb))
	{

		var bitmapData = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height),
		   ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
		try
		{
			// we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
			System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0,
			   pixelData.Pixels.Length);
		}
		finally
		{
			bitmap.UnlockBits(bitmapData);
		}
		filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"datamatrix_{DateTime.Now:yyyyMMddHHmmss}.png");
		bitmap.Save(filePath, ImageFormat.Png);
		Console.WriteLine($"DataMatrix 二维码已生成并保存至:{filePath}");

	}
}
catch (Exception ex)
{
	Console.WriteLine($"生成二维码时出错:{ex.Message}");
}

//解码
// 要解码的图片文件路径
// 1. 加载图片(替换为你的二维码路径)
string imagePath = filePath;
if (!File.Exists(imagePath))
{
	Console.WriteLine("图片不存在");
	return;
}
try
{
	var render = new BarcodeReader();
	render.Options = new ZXing.Common.DecodingOptions
	{
		CharacterSet = "UTF-8", // 指定解码时使用的字符集
		PureBarcode = true // 只解码纯条形码
	};
	var result = render.Decode(new Bitmap(imagePath));
	Console.WriteLine($"二维码解析内容:{result?.Text}");
}
catch (Exception ex)
{
	Console.WriteLine($"解码二维码时出错:{ex.Message}");
}

项目是 .net core8 的控制台 编码生成二维码和解码读取二维码有需要自行取用把;

这是生成的二维码效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值