Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
QR codes have become ubiquitous in our digital world, frequently used in advertising, retail, event management, and more. For developers working in the ASP.NET framework, integrating QR code scanning capabilities into web applications can enhance user experience and functionality. This article explores the process of implementing a QR code scanner in an ASP.NET application, covering the required tools, libraries, and step-by-step implementation. We will use IronQR, a powerful library for QR code generation from Iron Software to read QR codes.
QR (Quick Response) codes are two-dimensional barcodes that can store information ranging from URLs to contact details, typically scanned using smartphones or dedicated scanning devices. In web applications, QR codes can serve various purposes, such as:
IronQR is a powerful .NET library designed for QR code generation and scanning, providing robust functionality with ease of use in mind. This versatile library not only handles QR codes but can also manage other types of barcodes, making it a preferred choice for developers working within the .NET ecosystem. Here, we will explore how to integrate the IronQR library into an ASP.NET application to facilitate QR code scanning.
IronQR of .NET API products, which includes various tools for office documents, PDF editing, OCR, and more.
Start by creating a new Project and selecting the MVC template as shown below
Next, you should provide a project name and location for the project.
Select .NET version.
Clicking the create button will create the following code and project.
Install IronQR library from the Visual Studio package manager as shown below
IronQR can also be installed using NuGet Package Manager.
Now, let's create a QR code App.
QrCode
Modelusing System.ComponentModel.DataAnnotations;
namespace IronQRScannerAsp.Models
{
public class QRCodeModel
{
[Display(Name = "Select QR Image")]
public IFormFile QRCodeImage
{
get;
set;
}
}
}
using System.ComponentModel.DataAnnotations;
namespace IronQRScannerAsp.Models
{
public class QRCodeModel
{
[Display(Name = "Select QR Image")]
public IFormFile QRCodeImage
{
get;
set;
}
}
}
Imports System.ComponentModel.DataAnnotations
Namespace IronQRScannerAsp.Models
Public Class QRCodeModel
<Display(Name := "Select QR Image")>
Public Property QRCodeImage() As IFormFile
End Class
End Namespace
Add a new controller, by right-clicking on the controller folder and providing a name shown below:
Select Empty Controller.
Provide controller name.
Now add the following code to the controller.
using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace IronQRScannerAsp.Controllers
{
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult Index()
{
ViewBag.QrCodeText = "Text";
return View();
}
[HttpPost]
public IActionResult ScanQRCode(QRCodeModel qrImage)
{
string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
using (var stream = System.IO.File.Create(filePath))
{
qrImage.QRCodeImage.CopyTo(stream);
}
// 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 an get all embedded QR Codes
IEnumerable<QrResult> results = reader.Read(imageInput);
ViewBag.QrCodeText = results.First().Value;
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
ViewBag.QrCodeUri = imageUrl;
return View();
}
}
}
using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace IronQRScannerAsp.Controllers
{
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult Index()
{
ViewBag.QrCodeText = "Text";
return View();
}
[HttpPost]
public IActionResult ScanQRCode(QRCodeModel qrImage)
{
string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
using (var stream = System.IO.File.Create(filePath))
{
qrImage.QRCodeImage.CopyTo(stream);
}
// 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 an get all embedded QR Codes
IEnumerable<QrResult> results = reader.Read(imageInput);
ViewBag.QrCodeText = results.First().Value;
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
ViewBag.QrCodeUri = imageUrl;
return View();
}
}
}
Imports IronQr
Imports IronQRScannerAsp.Models
Imports IronSoftware.Drawing
Imports Microsoft.AspNetCore.Mvc
Namespace IronQRScannerAsp.Controllers
Public Class QrCodeController
Inherits Controller
Private ReadOnly _environment As IWebHostEnvironment
Public Sub New(ByVal environment As IWebHostEnvironment)
_environment = environment
End Sub
Public Function Index() As IActionResult
ViewBag.QrCodeText = "Text"
Return View()
End Function
<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
Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png")
Using stream = System.IO.File.Create(filePath)
qrImage.QRCodeImage.CopyTo(stream)
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 an get all embedded QR Codes
Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)
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
The provided code snippet is for an ASP.NET Core MVC controller named QrCodeController, which is designed to handle QR code scanning functionalities using the IronQR library. Here's a brief description of what the code does:
It constructs a file path (path) within the application's web root directory specifically for saving QR code images ("ScanQRCode" directory).
It checks if this directory exists, and if not, creates it to avoid any file not found errors when saving the file.
It constructs the full file path (filePath
) where the uploaded QR code image will be saved ("ScanQRCode/qrcode.png"). This overwrites any existing file with the same name, effectively handling new scans without accumulating files.
It opens a file stream and copies the content of the uploaded image (qrImage.QRCodeImage
, likely a form file) to the specified location on the server.
Utilizes AnyBitmap.FromFile(filePath)
to load the saved image file into a format suitable for QR code scanning. AnyBitmap
likely serves as a helper class for converting image files into a bitmap object that the QR reader can process.
Wraps the loaded bitmap into a QrImageInput
, which is specifically designed to be an input for the QR code reading process. Instantiates a QrReader
, a component of the IronQR library configured to detect and decode QR codes.
Calls reader.Read(imageInput)
to scan the image for QR codes. This method returns an IEnumerable<QrResult>
, where each QrResult
contains data from a detected QR code in the image. It extracts the first result's value using results.First().Value
and store this decoded information in ViewBag.QrCodeText
. This assumes the image contains at least one QR code and does not handle potential errors where no QR codes are detected.
Constructs a URL (imageUrl
) pointing to the saved QR code image on the server. This URL is constructed using the current HTTP request's scheme, host, and path base, ensuring it's accessible to users for viewing. The constructed URL is saved in ViewBag.QrCodeUri
.
Returns the same view (View()
), which likely displays both the QR code image and the decoded text to the user. The ViewBag
is used to pass the QR code's decoded text and the URL of the image to the view for rendering.
Add a new view, right-click on the CreateQRCode
action method in the QrCodeController
class.
Select the option "Add View" then select "Razor View". Click on "Add".
Then select the "Create" template and Model class generated previously.
Now replace the code in the view class with the one shown below.
@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">
</div>
<div class="form-group">
<h3>Scanned Text:</h3>
<h4>@ViewBag.QrCodeText</h4>
</div>
<div class="form-group">
<img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Clear</a>
</div>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
@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">
</div>
<div class="form-group">
<h3>Scanned Text:</h3>
<h4>@ViewBag.QrCodeText</h4>
</div>
<div class="form-group">
<img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Clear</a>
</div>
@section Scripts {
@{
await Html.RenderPartialAsync("_ValidationScriptsPartial");
}
}
model ReadOnly Property () As IronQRScannerAsp.Models.QRCodeModel
ViewData("Title") = "ScanQRCode"
End Property
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <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"> </div> <div class="form-group"> <h3> Scanned Text:</h3> <h4> @ViewBag.QrCodeText</h4> </div> <div class="form-group"> <img src="@ViewBag.QrCodeUri" class="img-thumbnail" /> </div> </form> </div> </div> <div> <a asp-action="Index"> Clear</a> </div> @section Scripts
"form-group"> </div> <div class="form-group"> (Of h3) Scanned Text
Inherits </h3>(Of h4) ViewBag.QrCodeText</h4> </div> <div class="form-group"> <img src="@ViewBag.QrCodeUri" class="img-thumbnail" /> </div> </form> </div> </div> (Of div) <a asp-action="Index"> Clear</a> </div> section Scripts
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Friend <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"> </div> <div class
"text-danger"></div> <div class="form-group"> </div> <div class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Friend <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
"ModelOnly" class="text-danger"></div> <div class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Friend <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
"multipart/form-data"> <div asp-validation-summary="ModelOnly" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Friend <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
"ScanQRCode" enctype="multipart/form-data"> <div asp-validation-summary
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action="ScanQRCode" enctype
"col-md-14"> <form asp-action="ScanQRCode" enctype
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action
"row"> <div class="col-md-14"> <form asp-action
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
Private Private Private Private Private Private Private Friend (Of h1) ScanQRCode</h1> (Of h4) QRCodeModel</h4> <hr /> <div Class="row"> <div class
@
If True Then
Await Html.RenderPartialAsync("_ValidationScriptsPartial")
End If
End Class
Now in the program.cs change the following code to make the above view as the default route
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}")
This changes the default route from HomeController
to our QrCode
Controller.
Input Image with URL: https://ironsoftware.com/csharp/qr.
On the page, select a QR code image and click upload to decode the QR code. This app can also be modified to read from a Video feed and display results.
To read advanced QR codes, IronQR provides the following settings.
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;
var inputBmp = AnyBitmap.FromFile("QrImage.png");
// Use Auto => Machine Learning Scan
// Careful Scan => Useful for scanning documents slowly and carefully
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 => For scanning frames from a camera
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);
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;
var inputBmp = AnyBitmap.FromFile("QrImage.png");
// Use Auto => Machine Learning Scan
// Careful Scan => Useful for scanning documents slowly and carefully
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 => For scanning frames from a camera
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);
Imports IronQr
Imports IronSoftware.Drawing
Imports IronQr.Enum
Imports System.Collections.Generic
Private inputBmp = AnyBitmap.FromFile("QrImage.png")
' Use Auto => Machine Learning Scan
' Careful Scan => Useful for scanning documents slowly and carefully
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 => For scanning frames from a camera
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)
By leveraging the latest in ML technology, we have elevated the QR code reader to new heights. The sophisticated ML model enhances the accuracy and efficiency of applications in decoding QR codes, even under complex conditions. Whether reading QR codes from still images, video streams, or live camera feeds, the ML-powered solution delivers the required information quickly and reliably. This innovation streamlines data retrieval and boosts security by identifying genuine QR codes and flagging potential threats. With our ML technology, you can be confident that your QR code scanning capabilities are at the cutting edge, providing your users with a smooth and secure experience
Developers can get an IronQR trial license from here. The Key needs to be placed in the appSettings.json.
{
"IronQR.License.LicenseKey": "My key"
}
In this article, we've explored how to scan QR codes in ASP.NET Core using IronQR. Integrating IronQR into an ASP.NET application for QR code scanning is a straightforward process that enhances the capabilities of web applications, making them more interactive and user-friendly. IronQR's powerful features and ease of use make it an excellent choice for developers looking to implement barcode-related functionalities.
9 .NET API products for your office documents