使用.Net Core 生成条形码,保存成图片,使用ZXing
转载于作者Lucas汪星人:https://www.jianshu.com/p/9955b4f27501
在原先作者的基础上根据我自己修改了一些代码仅供参考:
首先需要引用NuGet包:ZXing.Net.Bindings.ZKWeb.System.Drawing
也可以使用终端开发者PowerShell使用指令安装:dotnet add package ZXing.Net.Bindings.ZKWeb.System.Drawing
然后可以自己去写一个Demo创建一个MVC控制器写入以下代码:
/// <summary>
/// 生成条形码,保存成图片,使用了ZXing
/// </summary>
public IActionResult GenerateQRimage(string content)//public static byte[] GenerateQRimage(string content)
{
//初始化条形码格式,宽高,以及PureBarcode=true则不会留白框
var writer = new BarcodeWriterPixelData
{
Format = BarcodeFormat.CODE_128,//编码格式CODE_128或者CODABAR
Options = new EncodingOptions { Height = 31, Width = 167, PureBarcode = true, Margin = 1 }
};
var pixelData = writer.Write(content);
using (var bitmap = new System.DrawingCore.Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppRgb))
using (var ms = new MemoryStream())
{
var bitmapData = bitmap.LockBits(new System.DrawingCore.Rectangle(0, 0, pixelData.Width, pixelData.Height),
System.DrawingCore.Imaging.ImageLockMode.WriteOnly, System.DrawingCore.Imaging.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);
}
// save to stream as PNG
bitmap.Save(ms, System.DrawingCore.Imaging.ImageFormat.Png);
System.DrawingCore.Image image = System.DrawingCore.Bitmap.FromStream(ms, true);
image.Save("D:\\2010-asmart-healthcare\\SmartHealthcare\\SmartHealthcare.Web\\wwwroot\\barcodeimg\\" + content + ".png");
byte[] bytes = ms.GetBuffer();
if (bytes != null)
{
return Ok("生成成功");
}
else
{
return Ok("生成失败");
}
}
}
在这段代码中要注意引用的命名空间,如:System.DrawingCore 具体的情况请在使用到你的项目中去解决大概率就是命名空间的原因,还有代码中
image.Save("D:\\2010-asmart-healthcare\\SmartHealthcare\\SmartHealthcare.Web\\wwwroot\\barcodeimg\\" + content + ".png");具体的路径可以自己去自定义,比如可以保存到你自己的电脑文件夹中,改路径就行了。
然后创建一个MVC视图也是写一个小Demo去测试,代码如下:
@{
Layout = null;
}
<div>
<header>
<button id="imgOn">生成条形码</button>
@*url: '/BarCode/GetBarCode?message=' + message + "&gifFileName=" + "D:/test/test.gif" + "&width=" + 100 + "&height=" + 50,*@
</header>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
$("#imgOn").click(function () {
var message = "456789";
$.ajax({
url: '/BarCode/GenerateQRimage?content=' + message,
type: 'get',
success: function (res) {
console.log(res);
}
})
})
</script>
代码中的message可以自定义条形码中扫描出来的具体内容 比如我在代码中写的456789,那么我扫描条形码识别出来的内容就是456789
后端接受的参数名字叫content,具体的实现就需要结合具体的业务。
然后就可以生成条形码了。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?