基于Asp.Net Core,利用ZXing来生成二维码的一般流程

时间:2023-01-30 19:53:36

  本文主要介绍如何在.net环境下,基于Asp.Net Core,利用ZXing来生成二维码的一般操作。对二维码工作原理了解,详情见:https://blog.csdn.net/weixin_36191602/article/details/82466148文章介绍。

1、前期准备

  .net core preview8,vs2019(用于支持core3.0),二维码生成插件:开源库ZXIng。相关插件可以在github上找到。安装vs2019后新建.net core web解决方案,也可以右键该解决方案,通过管理解决方案Nuget包功能来找到。如下图:浏览中搜索Zxing第一个既是。选中安装即可。

基于Asp.Net Core,利用ZXing来生成二维码的一般流程

  可通过项目中依赖性查看相应包的引用。如图:

基于Asp.Net Core,利用ZXing来生成二维码的一般流程

 2.二维码生成

2.1前端页面

在login.cshtml页面中添加前端元素,主要是一个图片控件。

 <div style="text-align:center">
<div style="margin-top:20px">
<span>扫码获取</span><br/>
<img id="barcode" width="400" height="400" alt="扫码获取" src="Dynpass/GetBarCode"/>
</div>
</div>
src="Dynpass/GetBarCode"表示image数据从DynpassController的GetBarCode方法获取。

2.1后端代码

初始化界面以及二维码资源生成方法:

  public class DynPassController : Controller
{
private readonly BarCodeVue _barCodeContent;//
public DynPassController(IOptions<BarCodeVue> content)
{
this._barCodeContent = content.Value;
} /// <summary>
/// 初始化显示页面
/// </summary>
/// <returns></returns>
[HttpGet]
public IActionResult Login()
{
return View();
} /// <summary>
/// Svn显示==请求获取二维码资源
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult GetBarCode()
{
var bar= _barCodeContent != null ? _barCodeContent.BarCode : "扫码获取";
Bitmap bitmap = MyZxingBarcode.GenerateBitmapCode(bar);//扫码获取
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
return File(ms.GetBuffer(), "image/png");//
}
}
DynPassController生成二维码的内容即_barCodeContent值由core框架依赖注入(构造该对象时通过构造函数传入)。所以需在ConfigureServices中进行注册。
Barcode类结构
  public class BarCodeVue
{
public string BarCode { get; set; }
}
二维码内容注册

具体步骤:

1.在appsettings.json中添加节点。

 {
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"BarCodeVue": {
"BarCode":"MyBarCode"
}, "AllowedHosts": "*"
}

2.BarCodeVue注册

在Program类中ConfigureServices方法中通过Configure注册。

  // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
});
services.Configure<BarCodeVue>(Configuration.GetSection("BarCodeVue"));//注册BarCodeVue键值
//services.AddMvc().AddViewOptions(options => options.HtmlHelperOptions.ClientValidationEnabled = true);
services.AddControllersWithViews()
.AddNewtonsoftJson();
services.AddRazorPages();
}

3.生成二维码方法MyZxingBarcode类

  public class MyZxingBarcode
{
/// <summary>
/// 生成二维码,保存成图片
/// </summary>
public static Bitmap GenerateBitmapCode(string content)
{
var writer = new BarcodeWriterPixelData();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options.DisableECI = true;
//设置内容编码
options.CharacterSet = "UTF-8";
//设置二维码的宽度和高度
options.Width = ;
options.Height = ;
//设置二维码的边距,单位不是固定像素
options.Margin = ;
writer.Options = options;
//
var pixdata = writer.Write(content);
var map = PixToBitmap(pixdata.Pixels, pixdata.Width, pixdata.Height);
//string filename = @"D:\generate1.png";
//map.Save(filename, ImageFormat.Bmp);
return map;
} /// <summary>
/// 将一个字节数组转换为位图
/// </summary>
/// <param name="pixValue">显示字节数组</param>
/// <param name="width">图像宽度</param>
/// <param name="height">图像高度</param>
/// <returns>位图</returns>
private static Bitmap PixToBitmap(byte[] pixValue, int width, int height)
{
//// 申请目标位图的变量,并将其内存区域锁定
var m_currBitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var m_rect = new Rectangle(, , width, height);
var m_bitmapData = m_currBitmap.LockBits(m_rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb); IntPtr iptr = m_bitmapData.Scan0; // 获取bmpData的内存起始位置 //// 用Marshal的Copy方法,将刚才得到的内存字节数组复制到BitmapData中
System.Runtime.InteropServices.Marshal.Copy(pixValue, , iptr, pixValue.Length);
m_currBitmap.UnlockBits(m_bitmapData);
//// 算法到此结束,返回结果 return m_currBitmap; ////初始化条形码格式,宽高,以及PureBarcode=true则不会留白框
//var writer = new BarcodeWriterPixelData
//{
// Format = BarcodeFormat.QR_CODE,
// Options = new ZXing.Common.EncodingOptions { Height = 31, Width = 167, PureBarcode = true, Margin = 1 }
//};
//var pixelData = writer.Write("123236699555555555559989966");
//using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, PixelFormat.Format32bppRgb))
//using (var ms = new MemoryStream())
//{
// var bitmapData = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height),
// System.Drawing.Imaging.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);
// }
// // save to stream as PNG
// bitmap.Save(ms, ImageFormat.Png);
// Image image = Bitmap.FromStream(ms, true);
// image.Save(@"D:\content.png");
// byte[] bytes = ms.GetBuffer();
//}
}
}

运行生成结果:

基于Asp.Net Core,利用ZXing来生成二维码的一般流程

遗留问题:

当barcode包含中文时,生成二维码扫码得出结果是乱码。网上找了一些解决方案均不行。有时间在研究吧。在此记录作个记录。