Saltar al pie de página
USANDO IRONQR
Cómo leer un código QR usando IronQR

Lector de códigos QR en C# (Tutorial paso a paso)

On-demand generation of new and varied barcodes is a crucial aspect of many commercial .NET Applications. The IronBarcode library makes doing this very quick, convenient, and easy when compared to other third-party options. This tutorial aims to illustrate how this is so.

1. Creating a New Project

Open Visual Studio and go to the File menu. Select New Project, and then select Console Application/Windows Forms/WPF Application. Barcodes can also be used on all types of applications. Further, you can use them with apps such as Webform/MVC/MVC Core.

C# QR Code Reader (Step by Step Tutorial), Figure 1: Configure your new project Configure your new project

Enter the project name and select the file path in the appropriate text box in Visual Studio. Next, click the Create button, and also select the required .NET Framework. The project will now generate the structure for the selected application. If you have selected the Console Application, it will now open the program.cs file where you can enter the code and build/run the application.

2. Install the IronBarcode NuGet Package

Now go to the Solution Explorer in Visual Studio and left-click the project. From the pop-up menu, select the NuGet Package Manager from the menu and search for "Barcode" as a keyword. Select the first result in the NuGet Package dialog and click the install option.

C# QR Code Reader (Step by Step Tutorial), Figure 2: Install IronBarcode library from NuGet Package Manager Install IronBarcode library from NuGet Package Manager

Alternatively, in Visual Studio follow these instructions: Go to Tools > NuGet Package Manager > Package Manager Console

Open the Package Manager Console tab. Type the line below:

Install-Package IronQR

C# QR Code Reader (Step by Step Tutorial), Figure 3: NuGet Package Manager Console NuGet Package Manager Console

Go to the following link to learn more about the latest version of the Barcode Reader SDK.

https://www.nuget.org/packages/Barcode

Next, the package will download all the DLL files and also add the reference of the DLL file in the current project as a .NET project reference.

The Visual Studio project is now ready to use with the code.

3. Adding Reference

Add the IronBarCode reference to the code as shown below, allowing the use of functions available in the IronBarcode library in .NET Core. To learn more about the barcode reader control, reading QR codes, components, support for QR code types, and the compatibility of the barcode reader SDK, please refer to this link: https://ironsoftware.com/csharp/barcode/

using IronBarCode;
using IronBarCode;
Imports IronBarCode
$vbLabelText   $csharpLabel

4. Creating a Barcode Instance

BarcodeReader is the static class that is used to read/create QR codes. It can be used without creating any object instance for the static class BarcodeReader. The barcode reader control offers the ability to scan 15 types of barcodes using a single function Read or ReadAsync. The IronBarcode library enables the reading of QR codes/barcodes from various sources:

  • String
  • Stream
  • Image
  • Bitmap

5. Read the Barcode Using String

QR codes and barcode images can be read easily using the .NET barcode reader library. The Read method is a static function that will scan QR code images and decode QR codes and barcodes into text. It accepts various types of image files like bitmap, PNG files, JPEG, TIFF, etc.

This Read function extracts QR code/barcode data from the image and retrieves the result as the object BarcodeResult. If the image file is not recognized by the code, it will return null.

The BarcodeResult has the following values:

  • BarcodeType
  • Value
  • Text
  • Binary value

BarcodeType is an enum data type and it returns the type of the barcode of the given input image. There are twenty-two barcode types supported by IronBarcode. It will return the type of barcode, which is applied to the given input image.

Value and text are also object-type values available on the BarcodeResult. Both value and text are string data types. That returns the string value of the barcode. Read method will read QR codes and barcodes and get the string value of the given barcode image into value/text. The binary value is the byte data type and returns the byte of the given image. Below is the quick response code which can be used in any .NET Windows Forms or .NET Standard Applications.

// Read a barcode from an image file
BarcodeResult result = BarcodeReader.Read("test.bmp");
// Check if the result is not null and matches the expected text
if (result != null && result.Text == "https://ironsoftware.com/csharp/barcode")
{
    System.Console.WriteLine("Success");
}
// Read a barcode from an image file
BarcodeResult result = BarcodeReader.Read("test.bmp");
// Check if the result is not null and matches the expected text
if (result != null && result.Text == "https://ironsoftware.com/csharp/barcode")
{
    System.Console.WriteLine("Success");
}
' Read a barcode from an image file
Dim result As BarcodeResult = BarcodeReader.Read("test.bmp")
' Check if the result is not null and matches the expected text
If result IsNot Nothing AndAlso result.Text = "https://ironsoftware.com/csharp/barcode" Then
	System.Console.WriteLine("Success")
End If
$vbLabelText   $csharpLabel

The above code demonstrates how to read QR codes and barcodes using the .NET barcode reader library. The code is straightforward to use, mapping a file from the system to a Bitmap object. It also decodes the QR code/barcode from the image and displays the result in the object. Below are the QR codes/barcodes provided in the code to scan for the encoded data.

C# QR Code Reader (Step by Step Tutorial), Figure 4: The barcode input The barcode input

6. Read Multiple Barcodes from a TIFF Image

The .NET barcode reader control allows the reading of multiple QR codes/barcodes from an image file using the same Read method, which is very easy to use.

Below is the sample code for reading multiple QR codes from the image:

// Configure barcode reader options
BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    ExpectBarcodeTypes = BarcodeEncoding.Code128,
    ExpectMultipleBarcodes = true,
};

// Read multiple barcodes from a TIFF image
BarcodeResult[] multiFrameResults = BarcodeReader.Read("Multiframe.tiff", options);
// Configure barcode reader options
BarcodeReaderOptions options = new BarcodeReaderOptions()
{
    ExpectBarcodeTypes = BarcodeEncoding.Code128,
    ExpectMultipleBarcodes = true,
};

// Read multiple barcodes from a TIFF image
BarcodeResult[] multiFrameResults = BarcodeReader.Read("Multiframe.tiff", options);
' Configure barcode reader options
Dim options As New BarcodeReaderOptions() With {
	.ExpectBarcodeTypes = BarcodeEncoding.Code128,
	.ExpectMultipleBarcodes = True
}

' Read multiple barcodes from a TIFF image
Dim multiFrameResults() As BarcodeResult = BarcodeReader.Read("Multiframe.tiff", options)
$vbLabelText   $csharpLabel

In the above code, QR codes are extracted from TIFF QR code images. The .NET barcode reader scans QR codes from the image from the system and returns the result as an array. In the above code, the barcode for Code128 is the only type scanned. If there are any other barcodes present on the image, they will be ignored.

7. Reading QR Code and Barcodes from PDF

This section demonstrates how to read the QR code from PDF documents. The QR code library will scan all the available pages and files for all the available QR codes, or focus on one specific type of barcode. When using IronBarcode, the library provides all relevant DLLs needed for a standard barcode reader, so there is no need to include any other DLL as a .NET project reference.

Below is the sample code which can be used to read QR codes/barcodes from PDF.

// Read barcodes from each page of a PDF document
PagedBarcodeResult[] pagedResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
// Process results for each page
foreach (PagedBarcodeResult pageRes in pagedResults)
{
    int pageNumber = pageRes.PageNumber;
    string value = pageRes.Value;
    Bitmap img = pageRes.BarcodeImage;
    BarcodeEncoding barcodeType = pageRes.BarcodeType;
    byte[] binary = pageRes.BinaryValue;
    Console.WriteLine(pageRes.Value);
}
// Read barcodes from each page of a PDF document
PagedBarcodeResult[] pagedResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");
// Process results for each page
foreach (PagedBarcodeResult pageRes in pagedResults)
{
    int pageNumber = pageRes.PageNumber;
    string value = pageRes.Value;
    Bitmap img = pageRes.BarcodeImage;
    BarcodeEncoding barcodeType = pageRes.BarcodeType;
    byte[] binary = pageRes.BinaryValue;
    Console.WriteLine(pageRes.Value);
}
' Read barcodes from each page of a PDF document
Dim pagedResults() As PagedBarcodeResult = BarcodeReader.ReadPdf("MultipleBarcodes.pdf")
' Process results for each page
For Each pageRes As PagedBarcodeResult In pagedResults
	Dim pageNumber As Integer = pageRes.PageNumber
	Dim value As String = pageRes.Value
	Dim img As Bitmap = pageRes.BarcodeImage
	Dim barcodeType As BarcodeEncoding = pageRes.BarcodeType
	Dim binary() As Byte = pageRes.BinaryValue
	Console.WriteLine(pageRes.Value)
Next pageRes
$vbLabelText   $csharpLabel

The above is the sample code to read QR codes/barcodes from a PDF file from a simple ReadPdf method. It can also provide detailed results for each barcode and its type.

Conclusion

.NET Barcode readers provide a simple and easy way to read QR codes or decode/create QR codes and barcodes with simple steps. IronBarcode DLL can be used on various environments like .NET Windows Forms Applications, Mobile Apps, Web Applications, MAUI, and Blazor using the .NET Framework or .NET Standard. Additionally, IronBarcode offers a wide range of customization options to improve barcode reading speed, such as crop regions or multi-threading, and the accuracy of the ML model. IronBarcode offers a free trial key, or you can currently buy five products from Iron Software for the price of just two.

Visit the licensing page for more information.

You can also download a zip file project.

Preguntas Frecuentes

¿Cómo puedo leer códigos QR en C#?

Puedes leer códigos QR en C# usando la biblioteca IronQR instalando el Paquete NuGet IronBarcode en Visual Studio, agregando las referencias necesarias y utilizando la clase BarcodeReader.

¿Cuáles son los pasos para comenzar un proyecto de lectura de códigos QR en Visual Studio?

Para comenzar un proyecto de lectura de códigos QR en Visual Studio, crea un nuevo proyecto, instala el paquete NuGet IronBarcode, agrega las referencias requeridas y usa la clase BarcodeReader para leer códigos QR de varias fuentes.

¿Puedo leer múltiples códigos QR de una sola imagen en C#?

Sí, la biblioteca IronQR te permite leer múltiples códigos QR de una sola imagen usando el método Read con opciones configuradas para múltiples códigos.

¿Cómo puedo extraer códigos QR de un documento PDF en C#?

Puedes usar el método ReadPdf en la biblioteca IronQR para escanear un documento PDF en busca de códigos QR y obtener resultados detallados de cada página.

¿Qué opciones de personalización están disponibles para la lectura de códigos QR en C#?

IronQR ofrece opciones de personalización como establecer regiones de recorte, habilitar el uso de múltiples hilos y ajustar la precisión del modelo de aprendizaje automático para mejorar el rendimiento de la lectura de códigos QR.

¿Es IronQR adecuado para aplicaciones comerciales?

Sí, IronQR está diseñado para aplicaciones comerciales .NET, proporcionando capacidades confiables y eficientes de lectura de códigos QR.

¿Qué entornos admiten la lectura de códigos QR con IronQR?

IronQR admite varios entornos .NET, incluidas aplicaciones Windows Forms, aplicaciones móviles, aplicaciones web, MAUI y Blazor usando .NET Framework o .NET Standard.

¿Dónde puedo encontrar información sobre la licencia para usar IronQR?

Para obtener información sobre la licencia para usar IronQR, visita la sección de licencias en el sitio web de Iron Software.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más