QRCoder是一个生成二维码的.Net library。此库体积小,无多余依赖项。使用方便,可以满足正常工作需要。
Nuget 引用QRCoder
image.png
生成一个core web 项目,在项目中进行QRCoder的Demo演示。
1、生成web项目
image.png
2、添加引用
image.png
3、新建上层QRCoder控制器 + 新建下层QRCider服务
image.png
4、编码 编写QRCoder的帮助服务类
public class QRCoderService
{
#region QRCode
/// <summary>
/// 生成jpeg 格式 二维码
/// </summary>
/// <param name="plainText">文本内容</param>
/// <param name="pixel">像素</param>
/// <returns></returns>
public Bitmap GetQRCode(string plainText, int pixel)
{
var generator = new QRCodeGenerator();
var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);//纠错程度
var qrCode = new QRCoder.QRCode(qrCodeData);
var bitmap = qrCode.GetGraphic(pixel);
return bitmap;
}
#endregion
#region 在二维码中间加入头像
/// <summary>
/// 在二维码中间加入头像
/// </summary>
/// <param name="plainText">文本内容</param>
/// <param name="pixel">像素</param>
/// <param name="logoPath"></param>
/// <returns></returns>
public Bitmap GetQRCodeWithLogo(string plainText, int pixel, string logoPath)
{
var generator = new QRCodeGenerator();
var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCoder.QRCode(qrCodeData);
var bitmap = qrCode.GetGraphic(pixel, System.DrawingCore.Color.Black, System.DrawingCore.Color.White, (Bitmap)Image.FromFile(logoPath), 15, 6);
return bitmap;
}
#endregion
#region 生成svg格式的矢量二维码
public string GetSvgQRCode(string plainText, int pixel)
{
var generator = new QRCodeGenerator();
var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);
var qrcode = new SvgQRCode(qrCodeData);
return qrcode.GetGraphic(pixel);
}
#endregion
}
1、注入上文帮助类至容器中
services.AddScoped<QRCoderService>();
2、控制器中描述方法
public class QRCoderController : Controller
{
private IHostingEnvironment _hostingEnvironment;
private readonly QRCoderService _qrCoderService;
public QRCoderController(QRCoderService qrCoderService, IHostingEnvironment hostingEnvironment)
{
_qrCoderService = qrCoderService;
_hostingEnvironment = hostingEnvironment;
}
#region 生成jpeg 格式 二维码
public IActionResult GetJPEGQRPic()
{
//获取QRCoder Bitmap
var bm = _qrCoderService.GetQRCode("hello world", 15);
var ms = new MemoryStream();
bm.Save(ms, ImageFormat.Jpeg);
return File(ms.GetBuffer(), "image/jpeg");
}
#endregion
}
#region 生成带Icon二维码
public IActionResult GetQRCodeWithLogo()
{
var logoPath = $"{_hostingEnvironment.WebRootPath}/icon.png";
var bm = _qrCoderService.GetQRCodeWithLogo("hello world", 15, logoPath);
var ms = new MemoryStream();
bm.Save(ms, ImageFormat.Jpeg);
return File(ms.GetBuffer(), "image/jpeg");
}
#endregion
#region 生成svg图片
public IActionResult GetSvgQRPic()
{
var svgText = _qrCoderService.GetSvgQRCode("http://www.baidu.com", 15);
string rootPath = _hostingEnvironment.WebRootPath;
string svgName = $"{Guid.NewGuid().ToString()}.svg";
string filePath = $"{rootPath}/{svgName}";
System.IO.File.WriteAllText(filePath, svgText);
var byts = System.IO.File.ReadAllBytes(filePath);
return File(byts, "image/svg", svgName);
}
#endregion