.NET Core(C#)使用ZXing.Net生成条码(Barcode)和二维码(QR code)图片及示例代码
Posted on 2022-10-20 13:56 火冰·瓶 阅读(2136) 评论(0) 编辑 收藏 举报本文主要介绍.NET Core(C#)中,使用ZXing.Net生成图片格式的二维码(QR code)和条码(Barcode)的方法, 以及相关的示例代码。
1、通过Nuget安装引用ZXing.Net
1)使用Nuget界面管理器
搜索“ZXing.Net.Bindings.ZKWeb.System.Drawing”
,在列表中分别找到它,点击"安装"
相关文档:VS(Visual Studio)中Nuget的使用
2)使用Package Manager命令安装
PM> Install-Package ZXing.Net.Bindings.ZKWeb.System.Drawing
3)使用.NET CLI命令安装
> dotnet add package ZXing.Net.Bindings.ZKWeb.System.Drawing
2、命名空间
using System;
using System.IO;
using System.DrawingCore;
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
using ZXing.ZKWeb;
3、使用ZXing.Net生成条码图片
/// <summary>
/// 生成条形码
/// </summary>
/// <param name="message">条码信息</param>
/// <param name="gifFileName">生成条码图片文件名</param>
/// <param name="width">宽度</param>
/// <param name="height">高度</param>
public static void CreateBarCode(string message, string gifFileName, int width, int height)
{
if (string.IsNullOrWhiteSpace(message))
{
return;
}
var w = new ZXing.OneD.CodaBarWriter();
BitMatrix b = w.encode(message, BarcodeFormat.CODE_128, width, height);
var zzb = new ZXing.ZKWeb.BarcodeWriter();
zzb.Options = new EncodingOptions()
{
Margin = 3,
PureBarcode = false
};
string dir = Path.GetDirectoryName(gifFileName);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
Bitmap b2 = zzb.Write(b);
b2.Save(gifFileName, ImageFormat.Gif);
b2.Dispose();
}
4、使用ZXing.Net生成二维码图片
/// <summary>
/// 生成二维码返回byte数组
/// </summary>
/// <param name="message"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static byte[] CreateCodeBytes(string message, int width = 600, int height = 600)
{
int heig = width;
if (width > height)
{
heig = height;
width = height;
}
if (string.IsNullOrWhiteSpace(message))
{
return null;
}
var w = new QRCodeWriter();
BitMatrix b = w.encode(message, BarcodeFormat.QR_CODE, width, heig);
var zzb = new BarcodeWriter();
zzb.Options = new EncodingOptions()
{
Margin = 0,
};
Bitmap b2 = zzb.Write(b);
byte[] bytes = BitmapToArray(b2);
return bytes;
}
//将Bitmap 写为byte[]的方法
public static byte[] BitmapToArray(Bitmap bmp)
{
byte[] byteArray = null;
using (MemoryStream stream = new MemoryStream())
{
bmp.Save(stream, ImageFormat.Png);
byteArray = stream.GetBuffer();
}
return byteArray;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理