Asp.Net Core 生成二维码(NuGet使用QRCoder)

您所在的位置:网站首页 二维码的用法有哪些 Asp.Net Core 生成二维码(NuGet使用QRCoder)

Asp.Net Core 生成二维码(NuGet使用QRCoder)

2024-05-08 14:39| 来源: 网络整理| 查看: 265

前言

功能:调用web api 接口

1.获取 jpeg 格式的二维码 

2.获取中间带有logo 的二维码

3. 下载 jpeg,svg 格式的二维码

需要的NuGet 包:

> QRCoder(v1.3.6)

> System.Drawing.Common(v4.5.1)

 

正文

1. 准备项目

创建ASP.NET Core Web Api 应用程序,添加上边说的两个包,并创建Services 文件夹,Services 文件夹中的类如下:

 

2. 功能:生成jpeg 格式 二维码,通过Api 来请求

在 IQRCodeService 中添加定义的方法,返回的类型为Bitmap,引用Stytem.Drawing

using System.Drawing;

namespace QRCode.Api.Services.Interfaces{ public interface IQRCodeService {   Bitmap GetQRCode(string url, int pixel);

}}

在QRCodeService 中继承 IQRCodeService接口,实现 GetQRCode 方法。

using QRCode.Api.Services.Interfaces; using QRCoder; using System.Drawing; namespace QRCode.Api.Services { public class QRCodeService : IQRCodeService { #region QRCode 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 } }

上图: plainText 参数指的是 扫描二维码时显示的文本内容,pixel 参数指的是 像素

ECCLevel.Q 参数是 指:纠错程度,(The error correction level. Either L (7%), M (15%), Q (25%) or H (30%). Tells how much of the QR Code can get corrupted before the code isn't readable any longer.)

在Startup 中的ConfiguraServices 注入依赖

public void ConfigureServices(IServiceCollection services) { services.AddTransient(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }

在Controller 类中注入QRCodeservice 依赖,使用get 的请求方式,请求参数为plainText, pixel

     private readonly IQRCodeService _qrCode;

     public ValuesController(IQRCodeService qrCode) { _qrCode = qrCode; } [HttpGet("qrCode")] public IActionResult Get(string plainText, int pixel) { if (string.IsNullOrEmpty(plainText)) { return BadRequest("parameter is null"); } if (pixel


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3