如何在 ASP .NET 中掃描 QR 碼
QR碼在我們的數位世界中已經無處不在,經常被用於廣告、零售、活動管理等領域。 對於在ASP.NET框架中工作的開發者來說,將QR碼掃描功能整合到網頁應用中可以提高使用者體驗和功能性。 本文探討在ASP.NET應用中實現QR碼掃描器的過程,包括所需的工具、程式庫和步驟。 我們將使用IronQR,一個強大的Iron Software程式庫來讀取QR碼。
如何在ASP.NET中掃描QR碼
- 使用Visual Studio建立一個ASP.NET專案。
- 從套件管理器安裝IronQR程式庫。
- 上傳QR圖像並讀取QR。
- 讀取高級QR碼。
了解QR碼及其使用案例
QR(快速響應)碼是可以儲存資訊的二維條碼,從URL到聯繫方式,通常使用智能手機或專門的掃描裝置進行掃描。 在網頁應用中,QR碼可以用於多種用途,例如:
- 快速網站存取:使用者可以直接前往特定URL,而無需輸入地址。
- 活動票務:驗證活動接入票上的QR碼。
- 支付系統:通過掃描QR碼進行簡單支付。
- 產品資訊:提供有關產品的更多資訊。
IronQR介紹
IronQR 是一個強大的.NET程式庫,專為QR碼生成和掃描而設計,提供了強大的功能且易於使用。 這個多功能的程式庫不僅可以處理QR碼,還可以管理其他型別的條碼,是.NET生態系統中開發者的首選。 在這裡,我們將探討如何將IronQR程式庫整合到ASP.NET應用中以促進QR碼掃描。
IronQR的主要優勢和特點
-
讀取QR碼: IronQR可以從各種圖像格式中讀取QR碼,包括jpg、png、svg、bmp、gif、tif、tiff等。 它還支持多頁圖像和自定義QR檢測模型。 輸出資料格式包括文字、URL、坐標等。
-
寫入QR碼: 您可以生成QR碼並將其保存成圖像(jpg、png、gif、tiff、bmp)、流,甚至將其郵件到現有PDF文件中。 編碼資料如文字、URL、位元組和數字並生成QR碼。 通過調整大小、調整邊距、更改顏色和新增標誌來自定義QR碼樣式。
-
錯誤處理和校正: IronQR 提供詳細的錯誤資訊和自定義QR錯誤校正。 它確保故障容錯並支持空檢查和檢查碼。
-
高級機器學習模型: IronQR 使用高級機器學習模型進行QR碼識別。 這個模型在包括移動、桌面和雲環境在內的多個平台上確保準確可靠的QR碼讀取。
-
跨平台相容性: IronQR 適用於C#、F# 和VB.NET,運行在各種.NET版本上,如 .NET Core (8, 7, 6, 5, 及 3.1+)、.NET Standard (2.0+)、.NET Framework (4.6.2+)。
-
它支持不同的專案型別,包括網頁(Blazor & WebForms)、移動裝置(Xamarin & MAUI)、桌面(WPF & MAUI)和控制台應用。
- 廣泛的QR碼支持: IronQR 擅長處理各種QR碼和其他型別的條碼。 無論您是在處理標準的QR碼、Micro QR碼、QR條碼圖像,還是特定格式如Aztec或Data Matrix,IronQR 都能滿足需求。 IronQR 還支持讀取QR條碼的功能。
IronQR 是.NET API產品的一部分,包含了各種辦公文件、PDF編輯、OCR等工具。
步驟 1:使用Visual Studio建立一個新的ASP.NET專案
首先建立一個新專案並選擇如下所示的MVC模板:

接下來,您應該為專案提供一個名稱和位置。

選擇 .NET 版本。

按下建立按鈕將會建立以下程式碼和專案。

步驟 2:從Visual Studio套件管理器中安裝IronQR程式庫
按照下圖所示,從Visual Studio套件管理器中安裝IronQR程式庫:


步驟 3:上傳QR圖像並讀取QR圖像
現在,讓我們建立一個QR碼應用。
建立QRCodeModel
// Import necessary namespaces
using System.ComponentModel.DataAnnotations;
namespace IronQRScannerAsp.Models
{
public class QRCodeModel
{
// Property to hold the uploaded QR code image
[Display(Name = "Select QR Image")]
public IFormFile QRCodeImage { get; set; }
}
}
// Import necessary namespaces
using System.ComponentModel.DataAnnotations;
namespace IronQRScannerAsp.Models
{
public class QRCodeModel
{
// Property to hold the uploaded QR code image
[Display(Name = "Select QR Image")]
public IFormFile QRCodeImage { get; set; }
}
}
' Import necessary namespaces
Imports System.ComponentModel.DataAnnotations
Namespace IronQRScannerAsp.Models
Public Class QRCodeModel
' Property to hold the uploaded QR code image
<Display(Name := "Select QR Image")>
Public Property QRCodeImage() As IFormFile
End Class
End Namespace
建立QR碼控制器
右鍵點擊控制器文件夾並新增一個新的控制器,然後提供一個名稱,如下所示:

選擇空控制器。

提供控制器名稱。

現在將以下程式碼新增到控制器中。
// Import necessary namespaces
using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace IronQRScannerAsp.Controllers
{
// Controller to handle QR code scanning functionalities
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
// Constructor for dependency injection of the hosting environment
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
// Displays the initial View
public IActionResult Index()
{
ViewBag.QrCodeText = "Text";
return View();
}
// Handles the POST request to scan a QR code
[HttpPost]
public IActionResult ScanQRCode(QRCodeModel qrImage)
{
string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Define the file path for saving the uploaded QR image
string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
using (var stream = System.IO.File.Create(filePath))
{
qrImage.QRCodeImage.CopyTo(stream); // Save uploaded image to server
}
// Open the asset to read a QR Code from
var bitmap = AnyBitmap.FromFile(filePath);
// Load the asset into QrImageInput
QrImageInput imageInput = new QrImageInput(bitmap);
// Create a QR Reader object
QrReader reader = new QrReader();
// Read the Input and get all embedded QR Codes
IEnumerable<QrResult> results = reader.Read(imageInput);
// Display scanned text and image on the view
ViewBag.QrCodeText = results.First().Value;
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
ViewBag.QrCodeUri = imageUrl;
return View();
}
}
}
// Import necessary namespaces
using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace IronQRScannerAsp.Controllers
{
// Controller to handle QR code scanning functionalities
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
// Constructor for dependency injection of the hosting environment
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
// Displays the initial View
public IActionResult Index()
{
ViewBag.QrCodeText = "Text";
return View();
}
// Handles the POST request to scan a QR code
[HttpPost]
public IActionResult ScanQRCode(QRCodeModel qrImage)
{
string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Define the file path for saving the uploaded QR image
string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
using (var stream = System.IO.File.Create(filePath))
{
qrImage.QRCodeImage.CopyTo(stream); // Save uploaded image to server
}
// Open the asset to read a QR Code from
var bitmap = AnyBitmap.FromFile(filePath);
// Load the asset into QrImageInput
QrImageInput imageInput = new QrImageInput(bitmap);
// Create a QR Reader object
QrReader reader = new QrReader();
// Read the Input and get all embedded QR Codes
IEnumerable<QrResult> results = reader.Read(imageInput);
// Display scanned text and image on the view
ViewBag.QrCodeText = results.First().Value;
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
ViewBag.QrCodeUri = imageUrl;
return View();
}
}
}
' Import necessary namespaces
Imports IronQr
Imports IronQRScannerAsp.Models
Imports IronSoftware.Drawing
Imports Microsoft.AspNetCore.Mvc
Namespace IronQRScannerAsp.Controllers
' Controller to handle QR code scanning functionalities
Public Class QrCodeController
Inherits Controller
Private ReadOnly _environment As IWebHostEnvironment
' Constructor for dependency injection of the hosting environment
Public Sub New(ByVal environment As IWebHostEnvironment)
_environment = environment
End Sub
' Displays the initial View
Public Function Index() As IActionResult
ViewBag.QrCodeText = "Text"
Return View()
End Function
' Handles the POST request to scan a QR code
<HttpPost>
Public Function ScanQRCode(ByVal qrImage As QRCodeModel) As IActionResult
Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "ScanQRCode")
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
' Define the file path for saving the uploaded QR image
Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png")
Using stream = System.IO.File.Create(filePath)
qrImage.QRCodeImage.CopyTo(stream) ' Save uploaded image to server
End Using
' Open the asset to read a QR Code from
Dim bitmap = AnyBitmap.FromFile(filePath)
' Load the asset into QrImageInput
Dim imageInput As New QrImageInput(bitmap)
' Create a QR Reader object
Dim reader As New QrReader()
' Read the Input and get all embedded QR Codes
Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)
' Display scanned text and image on the view
ViewBag.QrCodeText = results.First().Value
Dim imageUrl As String = $"{Me.Request.Scheme}://{Me.Request.Host}{Me.Request.PathBase}" & "/ScanQRCode/qrcode.png"
ViewBag.QrCodeUri = imageUrl
Return View()
End Function
End Class
End Namespace
程式碼說明
提供的程式碼片段是名為QrCodeController 的ASP.NET Core MVC控制器,旨在通過IronQR程式庫處理QR碼掃描功能。 以下是對程式碼所做的操作的簡要描述:
1. 保存上傳的QR碼圖像
路徑構建
- 它在應用程式的網站根目錄中構建保存QR碼圖像的文件路徑("ScanQRCode"目錄)。
- 它檢查此目錄是否存在,如無則建立它以避免在保存文件時出現找不到文件的錯誤。
文件保存
- 它構建了上傳的QR碼圖像將被保存的完整文件路徑("ScanQRCode/qrcode.png")。 這將覆蓋任何同名的現有文件,從而有效地處理新掃描而不會累積文件。
- 它打開一個文件流,並將上傳的圖像內容(
qrImage.QRCodeImage,可能是表單文件)複製到伺服器上的指定位置。
2. 解碼QR碼
讀取圖像文件
- 使用
AnyBitmap.FromFile(filePath)將保存的圖像文件載入到適合QR碼掃描的格式中。AnyBitmap可能作為輔助類進行圖像文件轉換為QR掃描處理的位圖物件。
初始化QR讀取器
- 將載入的位圖包裝到
QrImageInput中,這是專門為QR碼讀取過程設計的輸入。 - 實例化
QrReader,這是IronQR程式庫中的一個組件,用於檢測和解碼QR碼。
掃描QR碼
- 調用
reader.Read(imageInput)掃描圖像中的QR碼。 此方法返回QrResult包含圖像中的QR碼檢測到的資料。 - 它使用
results.First().Value提取第一個結果的值,並將此解碼的資訊儲存在ViewBag.QrCodeText中。 這假設圖像中至少包含一個QR碼,且未處理未檢測到QR碼時的潛在錯誤。
3. 準備和返回響應
圖像URL構建
- 構建指向伺服器上保存的QR碼圖像的URL(
imageUrl)。 此URL是使用當前HTTP請求的協議、主機和路徑基構建的,確保使用者可以存取以檢視。 - 構建的URL儲存在
ViewBag.QrCodeUri中。
視圖返回
- 返回同一視圖(
View()),該視圖可能同時顯示QR碼圖像和解碼文字給使用者。ViewBag用來將QR碼的解碼文字和圖像的URL傳遞給視圖以進行渲染。
將視圖新增到控制器類中
新增一個新的視圖,右鍵點擊QrCodeController類中。

選擇"新增視圖"選項,然後選擇"Razor視圖"。 點擊"新增"。

然後選擇建立模板和先前生成的Model類。

現在將視圖類中的程式碼替換為下方所示的程式碼。
@model IronQRScannerAsp.Models.QRCodeModel
@{
ViewData["Title"] = "ScanQRCode";
}
<h1>ScanQRCode</h1>
<h4>QRCodeModel</h4>
<hr />
<div class="row">
<div class="col-md-14">
<form asp-action="ScanQRCode" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label for="QRCodeImage">Select QR Image:</label>
<input asp-for="QRCodeImage" class="form-control" type="file" />
</div>
<div class="form-group">
<input type="submit" value="Upload" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<h3>Scanned Text:</h3>
<h4>@ViewBag.QrCodeText</h4>
@if (ViewBag.QrCodeUri != null)
{
<img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
}
</div>
<div>
<a asp-action="Index">Clear</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
現在在Program.cs中更改以下程式碼以將上述視圖設為預設路由:
app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=Index}");
app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=Index}");
app.MapControllerRoute(name:= "default", pattern:= "{controller=QrCode}/{action=Index}")
這將預設路由從QrCode控制器。
輸入圖像及URL:https://ironsoftware.com/csharp/qr/。

輸出

在頁面上,選擇一個QR碼圖像並點擊上傳以解碼QR碼。 此應用還可以修改為從影片源讀取並顯示結果。
步驟4:讀取高級QR碼
為了讀取高級QR碼,IronQR提供了以下設置。
// Import necessary namespaces
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;
// Load an image file as a bitmap
var inputBmp = AnyBitmap.FromFile("QrImage.png");
// Use Auto => Machine Learning Scan
QrImageInput scan_ML_and_normal = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results1 = new QrReader().Read(scan_ML_and_normal);
// Use Machine Learning Scan - High Speed
QrImageInput scan_ML_only = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results2 = new QrReader().Read(scan_ML_only);
// Use Scan without Machine Learning
QrImageInput scan_normal_only = new QrImageInput(inputBmp, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> results3 = new QrReader().Read(scan_normal_only);
// Import necessary namespaces
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;
// Load an image file as a bitmap
var inputBmp = AnyBitmap.FromFile("QrImage.png");
// Use Auto => Machine Learning Scan
QrImageInput scan_ML_and_normal = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results1 = new QrReader().Read(scan_ML_and_normal);
// Use Machine Learning Scan - High Speed
QrImageInput scan_ML_only = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results2 = new QrReader().Read(scan_ML_only);
// Use Scan without Machine Learning
QrImageInput scan_normal_only = new QrImageInput(inputBmp, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> results3 = new QrReader().Read(scan_normal_only);
' Import necessary namespaces
Imports IronQr
Imports IronSoftware.Drawing
Imports IronQr.Enum
Imports System.Collections.Generic
' Load an image file as a bitmap
Private inputBmp = AnyBitmap.FromFile("QrImage.png")
' Use Auto => Machine Learning Scan
Private scan_ML_and_normal As New QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel)
Private results1 As IEnumerable(Of QrResult) = (New QrReader()).Read(scan_ML_and_normal)
' Use Machine Learning Scan - High Speed
Private scan_ML_only As New QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel)
Private results2 As IEnumerable(Of QrResult) = (New QrReader()).Read(scan_ML_only)
' Use Scan without Machine Learning
Private scan_normal_only As New QrImageInput(inputBmp, QrScanMode.OnlyBasicScan)
Private results3 As IEnumerable(Of QrResult) = (New QrReader()).Read(scan_normal_only)
通過利用當前最先進的機器學習技術,我們提升了QR碼讀取器的新高度。 複雜的ML模型提高了應用程式在複雜條件下解碼QR碼的準確性和效率。 無論是在靜止圖像、影片流或現場攝像頭源中讀取QR碼,該ML驅動的解決方案都能迅速可靠地提供所需資訊。 這一創新簡化了資料檢索,通過識別真實QR碼並標記潛在的威脅來提高安全性。 有了我們的ML技術,您可以确信您的QR碼掃描能力處於前沿,為您的使用者提供流暢安全的體驗。
授權 (可試用)
開發者可以在這裡獲得IronQR試用授權。 需要將密鑰放置在appSettings.json中。
{
"IronQr.License.LicenseKey": "My Key"
}
結論
在這篇文章中,我們探討了如何使用IronQR在ASP.NET Core中掃描QR碼。 將IronQR整合到ASP.NET應用中以進行QR碼掃描是一個簡單的過程,可以增強網頁應用的功能,使之更加互動和使用者友好。 IronQR的強大功能和易用性使之成為開發者實現條碼相關功能的首選。
常見問題
如何在ASP.NET應用程式中實現QR碼掃描器?
要在ASP.NET應用程式中實現QR碼掃描器,首先在Visual Studio中建立一個新專案,通過套件管理器安裝IronQR程式庫,並新增程式碼來使用IronQR的強大功能處理QR碼掃描。
在ASP.NET中設置QRCodeModel有哪些步驟?
要在ASP.NET中設置QRCodeModel,定義一個模型類來處理QR碼資料,使用IronQR處理輸入,並確保您的ASP.NET應用程式可以管理QR碼掃描和顯示結果。
IronQR能否從不同的圖像格式讀取QR碼?
是的,IronQR可以從多種圖像格式讀取QR碼,包括jpg、png、svg、bmp、gif、tif、tiff和多頁圖像,非常適合各種應用。
IronQR是如何利用機器學習進行QR碼掃描的?
IronQR採用先進的機器學習模型來提高QR碼掃描的準確性,確保在多種環境和平台上的可靠和精確的讀取。
我可以在哪些平台上使用IronQR進行QR碼掃描?
IronQR支持包括Web應用程式(Blazor & WebForms)、移動應用程式(Xamarin & MAUI)、桌面應用程式(WPF & MAUI)和控制台應用程式,相容C#、F#和VB.NET。
如何在ASP.NET中處理QR碼掃描的檔案上傳?
在ASP.NET中,通過設置一個控制器接收文件來管理QR碼掃描的檔案上傳,然後使用IronQR有效地處理和掃描上傳的QR碼圖像。
是否可以使用IronQR從影片源掃描QR碼?
是的,IronQR可以適配於從影片源掃描QR碼,擴展其應用於需要實時資料處理的動態環境。
IronQR有哪些許可選項?
IronQR提供可在Iron Software網站獲得的試用許可證。開發者應將許可鑰匙放入appSettings.json文件以激活試用。
在ASP.NET中使用IronQR進行QR碼掃描有哪些好處?
在ASP.NET中使用IronQR進行QR碼掃描的好處包括易於整合、支持多種圖像格式、機器學習增強的準確性和跨平台的相容性。
如何在ASP.NET中使用IronQR自訂QR碼建立?
要在ASP.NET中使用IronQR自訂QR碼建立,可使用程式庫的功能修改QR碼大小、顏色和內嵌資料,將輸出調整為特定應用需求。




