前言
QRCoderr 是老牌 C# 產生 QR Code 的套件,從過去的 .NET Framework 就相當熱門。理所當然,.NET Core 也能使用此套件。 本篇文章將藉由一個簡單的 ASP.NET Core Web Application 範例,簡單介紹如何使用 QRCoder 產生 QR Code。若有錯誤或任何建議,請各位前輩不吝提出。介紹
第一次在專案使用 QRCoder 需要先從 Nuget 進行安裝:開啟工具 (Tools) > NuGet 套件管理員 (NuGet Package Manager) > 管理方案 NuGet 套件 (Manage NuGet Packer for Solution)
搜尋 QRCoder,點選你要安裝的專案,點選安裝...
下列是一個產生 QR Code 的範例:
第 2 行 data 為掃描出來後想呈現的資料;QRCodeGenerator.ECCLevel 為 QR Code 的修正等: L 為 7%、 M 為 15%、 Q 為 25% 或 H 為30%。
第 4 行 即產生QR Code 圖檔 (Bitmap)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
QRCodeGenerator qrGenerator = new QRCodeGenerator(); | |
QRCodeData qrCodeData = qrGenerator.CreateQrCode(data, QRCodeGenerator.ECCLevel.Q); | |
QRCode qrCode = new QRCode(qrCodeData); | |
Bitmap qrCodeImage = qrCode.GetGraphic(35); |
我們要將 Bitmap 存入站台內 wwwroot下 Images 資料夾,命名為 Code.png。之後需要 QR Code 時,只需要給圖片連接即可。這一個部分僅為範例,在您的專案,你可以依據情境來處理產生出來的 QR Code 圖片。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string outputFileName = @"wwwroot\Images\Code.png"; | |
using (MemoryStream memory = new MemoryStream()) | |
{ | |
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite)) | |
{ | |
qrCodeImage.Save(memory, ImageFormat.Jpeg); | |
byte[] bytes = memory.ToArray(); | |
fs.Write(bytes, 0, bytes.Length); | |
} | |
} |
上列就是簡單的 QRCoder 產生 QR Code 範例。理所當然還有更多應用,你可以參考:QRCoder
本篇文章的範例:QRCoderExample 範例下載 (ASP.NET Core MVC and Visual Studio 2019)
範例中,我們將檔案路徑透過 ViewBag.ImageUrl 傳至 View 使用:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ViewBag.ImageUrl = outputFileName.Replace("wwwroot",""); |
在View 中,我們透過 img 來顯示圖片:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<img src="@ViewBag.ImageUrl"/> |
參考資料
1. QRCoder
1 留言
請問可以調整 QRCode 的大小嗎 ?
回覆刪除