.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 二維碼方法,代碼如下

 1 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

            */

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM