.net core 生成二维码

其实生成二维码的组件有很多种,如:QrcodeNet,ZKWeb.Fork.QRCoder,QRCoder等

我选QRCoder,是因为小而易用、支持大并发生成请求、不依赖任何库和网络服务。

既然是.net core 那当然要用依赖注入,通过构造函数注入到控制器。

 

软件版本

Asp.net Core:2.0

QRCoder:1.3.3(开发时最新)

 

项目结构

Snai.QRCode.Api  Asp.net core 2.0 Api网站

项目实现

新建Snai.QRCode解决方案,在解决方案下新建一个名Snai.QRCode.Api Asp.net core 2.0 Api网站

在 依赖项 右击 管理NuGet程序包 浏览 找到 QRCoder 版本1.3.3 下载安装

由于使用依赖注入,依赖抽象不依赖实现,所以要建一个实现二维码的接口

在项目添加 Common 文件夹,在文件夹添加 IQRCode 二维码接口,接口定义 GetQRCode 二维码方法,代码如下

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;

namespace Snai.QRCode.Api.Common
{
    public interface IQRCode
    {
        Bitmap GetQRCode(string url, int pixel);
    }
}

在 Common 目录下添加 RaffQRCode 类,继承IQRCode接口实现GetQRCode类,代码如下

using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;

namespace Snai.QRCode.Api.Common
{
    public class RaffQRCode : IQRCode
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="url">存储内容</param>
        /// <param name="pixel">像素大小</param>
        /// <returns></returns>
        public Bitmap GetQRCode(string url, int pixel)
        {
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData codeData = generator.CreateQrCode(url, QRCodeGenerator.ECCLevel.M, true);
            QRCoder.QRCode qrcode = new QRCoder.QRCode(codeData);

            Bitmap qrImage = qrcode.GetGraphic(pixel, Color.Black, Color.White, true);

            return qrImage;
        }
    }
}

 修改Startup.cs代码,注入RaffQRCode类到容器

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Snai.QRCode.Api.Common;

namespace Snai.QRCode.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IQRCode, RaffQRCode>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

 在Controllers 下添加QRCodeController Api空的控制器,采用构造函数依赖,引入RaffQRCode类

添加GetQRCode(string url, int pixel)方法,加入HttpGet("/api/qrcode")路由地址,方法里使用_iQRCode.GetQRCode(url, pixel)生成二维码再输出

代码如下:

using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Snai.QRCode.Api.Common;

namespace Snai.QRCode.Api.Controllers
{
    public class QRCodeController : Controller
    {
        private IQRCode _iQRCode;

        public QRCodeController(IQRCode iQRCode)
        {
            _iQRCode = iQRCode;
        }

        /// <summary>
        /// 获取二维码
        /// </summary>
        /// <param name="url">存储内容</param>
        /// <param name="pixel">像素大小</param>
        /// <returns></returns>
        [HttpGet("/api/qrcode")]
        public void GetQRCode(string url, int pixel)
        {
            
            Response.ContentType = "image/jpeg";

            var bitmap = _iQRCode.GetQRCode(url, pixel);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);

            Response.Body.WriteAsync(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
            Response.Body.Close();
        }
    }
}

 到此所有代码都已编写完成

启动运行项目,在浏览器打开 http://localhost:5000//api/qrcode?url=http://www.baidu.com&pixel=4 地址,得到url参数域名的二维码

 

/* GetGraphic方法参数说明
                public Bitmap GetGraphic(int pixelsPerModule, Color darkColor, Color lightColor, Bitmap icon = null, int iconSizePercent = 15, int iconBorderWidth = 6, bool drawQuietZones = true)
            *
                int pixelsPerModule:生成二维码图片的像素大小 ,我这里设置的是5
            *
                Color darkColor:暗色   一般设置为Color.Black 黑色
            *
                Color lightColor:亮色   一般设置为Color.White  白色
            *
                Bitmap icon :二维码 水印图标 例如:Bitmap icon = new Bitmap(context.Server.MapPath("~/images/zs.png")); 默认为NULL ,加上这个二维码中间会显示一个图标
            *
                int iconSizePercent: 水印图标的大小比例 ,可根据自己的喜好设置
            *
                int iconBorderWidth: 水印图标的边框
            *
                bool drawQuietZones:静止区,位于二维码某一边的空白边界,用来阻止读者获取与正在浏览的二维码无关的信息 即是否绘画二维码的空白边框区域 默认为true

            */

Github源码地址:https://github.com/Liu-Alan/Snai.QRCode

博客地址:https://www.snaill.net/post/6

posted @ 2018-06-23 07:51  蜗牛丨  阅读(10030)  评论(12编辑  收藏  举报