1. 程式人生 > >建議收藏備用:.net core使用QRCoder生成普通二維碼和帶Logo的二維碼詳細使用教程,原始碼已更新至開源模板

建議收藏備用:.net core使用QRCoder生成普通二維碼和帶Logo的二維碼詳細使用教程,原始碼已更新至開源模板

隨著網際網路越來越生活化,二維碼的使用越來越普遍,不論是掃碼支付還是掃碼關注引流,似乎我們總是離不開二維碼,那麼很多需要推廣的文章或社群想要自己的二維碼,那麼你是不是需要在網站直接提供給使用者呢?很多開發者就在網上百度解決方案,邊做邊踩坑,甚至很多人寫的開發案例都是截圖或者類庫引用都沒說清楚,在這個摸索的途中造成很多時間上的浪費。

尤其是嘗試新技術那些舊的操作還會有所改變,為了節約開發時間,我們把解決方案收入到一個個demo中,方便以後即拿即用。而且這些demo有部落格文件支援,幫助任何人非常容易上手開發跨平臺的.net core。隨著時間的推移,我們的demo庫會日益強大請及時收藏GitHub。

一、首先在Common公用專案中引用QRCoder類庫

 Install-Package QRCoder -Version 1.3.3

二、在Common公用專案中建立QRCoderHelper類

        #region 普通二維碼
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">儲存內容</param>
        /// <param name="pixel">畫素大小</param>
        /// <returns></returns>
        public static Bitmap GetPTQRCode(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;
        }
        #endregion

        #region 帶logo的二維碼
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url">儲存內容</param>
        /// <param name="pixel">畫素大小</param>
        /// <returns></returns>
        public static Bitmap GetLogoQRCode(string url,string logoPath, int pixel)
        {
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData codeData = generator.CreateQrCode(url, QRCodeGenerator.ECCLevel.M, true);
            QRCoder.QRCode qrcode = new QRCoder.QRCode(codeData);
            Bitmap icon = new Bitmap(logoPath);
            Bitmap qrImage = qrcode.GetGraphic(pixel, Color.Black, Color.White, icon,15,6, true);
            #region 引數介紹
            //GetGraphic方法引數介紹
            //pixelsPerModule //生成二維碼圖片的畫素大小 ,我這裡設定的是5
            //darkColor       //暗色   一般設定為Color.Black 黑色
            //lightColor      //亮色   一般設定為Color.White  白色
            //icon             //二維碼 水印圖示 例如:Bitmap icon = new Bitmap(context.Server.MapPath("~/images/zs.png")); 預設為NULL ,加上這個二維碼中間會顯示一個圖示
            //iconSizePercent  //水印圖示的大小比例 ,可根據自己的喜好設定
            //iconBorderWidth  // 水印圖示的邊框
            //drawQuietZones   //靜止區,位於二維碼某一邊的空白邊界,用來阻止讀者獲取與正在瀏覽的二維碼無關的資訊 即是否繪畫二維碼的空白邊框區域 預設為true
            #endregion
            return qrImage;
        }
        #endregion

注意:如果你想做其它調整可以參考我第二個方法中的引數介紹進行設定,考慮到大家的難處,我把那些相關引數幫各位查了。

三、新增QRCodeController控制器處理請求並返回二維碼圖片

private readonly IWebHostEnvironment webHostEnvironment;
        //private readonly IHostingEnvironment _hostingEnvironment; 3.0之前使用它
        public QRCodeController(IWebHostEnvironment _webHostEnvironment)
        {
            webHostEnvironment=_webHostEnvironment;
        }
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult GetPTQRCode(string url, int pixel=5)
        {
            url = HttpUtility.UrlDecode(url);
            Response.ContentType = "image/jpeg";

            var bitmap = QRCoderHelper.GetPTQRCode(url, pixel);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/png");
        }
        public IActionResult GetLogoQRCode(string url,string logoPath, int pixel = 5)
        {
            url = HttpUtility.UrlDecode(url);
            logoPath= webHostEnvironment.WebRootPath + HttpUtility.UrlDecode(logoPath);
            Response.ContentType = "image/jpeg";

            var bitmap = QRCoderHelper.GetLogoQRCode(url, logoPath, pixel);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            return File(ms.ToArray(), "image/png");
        }

注意:其中IHostingEnvironment是.net core 3.0之前使用獲取目錄位置的,而我們.net core 3.0已經由IHostingEnvironment變更為IWebHostEnvironment來獲取了。

四、前端請求設計

<link href="~/Lib/Mobile/jquery.mobile-1.4.5.min.css" rel="stylesheet" />
<script src="~/Lib/Mobile/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript">
    $(function () {
        PTCreate();
        LogoCreate();
    });
    function PTCreate() {
        pt = escape($("#PT").val());//防止中文等特殊字元引起問題
        ptSize = $("#PTSize").val();
        var id = document.getElementById("PTImg");
        var str = "../QRCode/GetPTQRCode?url=" + pt + "&pixel=" + ptSize + "&random=" + Math.random();
        id.setAttribute("src", str);
    }
    function LogoCreate() {
        logo = escape($("#Logo").val());
        logoPath = escape($("#LogoPath").val());
        logoSize = $("#LogoSize").val();
        var id = document.getElementById("LogoImg");
        var str = "../QRCode/GetLogoQRCode?url=" + logo + "&logoPath=" + logoPath + "&pixel=" + logoSize + "&random=" + Math.random();
        id.setAttribute("src", str);
    }
</script>
<div style="width:60%; margin:auto;text-align:center;">
    <h2>普通二維碼</h2>
    <input type="text" class="form-control" id="PT" placeholder="請輸入字元" value="www.jiyuwu.com"><button onclick="PTCreate();">生成</button>
    <input type="range" name="points" id="PTSize" value="5" min="1" max="20" onchange="PTCreate();">
    <br />
    <img id="PTImg" />
    <h2>Logo二維碼</h2>
    <input type="text" class="form-control" id="Logo" placeholder="請輸入字元" value="www.jiyuwu.com">
    <input type="text" class="form-control" id="LogoPath" placeholder="logo位置" value="\Lib\Markdown\images\logos\editormd-logo-32x32.png">
    <button onclick="LogoCreate();">生成</button>
    <input type="range" name="points" id="LogoSize" value="5" min="1" max="20" onchange="LogoCreate();">
    <img id="LogoImg" />
</div>

五、那麼看下效果吧

開源地址 動動小手,點個推薦吧!

 

注意:我們機遇屋該專案將長期為大家提供asp.net core各種好用demo,旨在幫助.net開發者提升競爭力和開發速度,建議儘早收藏該模板集合專案。