Saltar al pie de página
USO DE IRONBARCODE
Cómo leer el escáner de código de barras en aplicaciones de Windows en C#

Uso de escáneres de códigos de barras en aplicaciones C#

This tutorial will demonstrate how to scan QR codes and barcodes in C# Console Applications and .NET Windows Forms Applications, using the IronBarcode library as an example.

Using the IronBarcode library, multiple barcodes can be scanned and read simultaneously, and it can also successfully scan imperfect images. Let's first clarify what a barcode scanner is.

What is a Barcode Scanner?

A barcode is a square or rectangular image consisting of a series of parallel black lines and white spaces of varying widths. A barcode scanner or barcode reader is a device that can read printed barcodes, decode the data contained in the barcode, and send the data to a computer.

The following steps will introduce how to create a barcode scanner with the help of the IronBarcode Library.

How to Read Barcodes in C#

  • Create a .NET Windows Forms Application project in Microsoft Visual Studio
  • Install the barcode library
  • Read any barcode or QR code
  • Read multiple barcodes or QR codes in a single scan
  • Allow IronBarcode to read from imperfect scans and photos

1. Create a Windows Forms Application in Microsoft Visual Studio

Open Visual Studio > Click on Create New Project > Select Windows Forms Application Template > Press Next > Name the Project > Press Next > Select your target .NET Framework > Click on the Create Button.

After creating the project, design the form as follows from the Visual Studio toolbox: PictureBox, Label, TextBox, and Button controls.

How to Use Barcode Scanners in C# Windows Application, Figure 1: Barcode Scanner Barcode Scanner

2. Install the Barcode .NET Library in C#

The Barcode Library can be installed using one of the following three methods:

1. Package Manager Console

Write the following command in the Package Manager Console. It will download and install the package for you.

Install-Package BarCode

2. NuGet Packages Manager Solution

You can also install the Barcode Library by using the NuGet Package Solution. Simply follow these steps:

Click on Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

This will open NuGet Package Manager for you. Click on Browse and search for Barcode, then install the class library.

As an alternative, the IronBarCode.Dll can be downloaded and added to your project as a reference.

After downloading, add the following references to your barcode reader project.

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

3. Read any Barcode or QR Code

Reading a barcode or QR code in .NET is incredibly easy using the IronBarcode library with .NET Barcode Reader.

Barcode Scanner

In your project, browse for the image you wish to read. It will open in PictureBox; now click on "scan code". The text will appear in the text box.

Here is the code for the "browse" button to open an image:

// Open file dialog   
OpenFileDialog open = new OpenFileDialog();
// Image filters  
open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg;*.png;*.jpeg;*.gif;*.bmp";
if (open.ShowDialog() == DialogResult.OK) {  
    // Display image in PictureBox
    pictureBox1.Image = new Bitmap(open.FileName); 
    // Store image file path in class data member. Initialize it as string ImageFileName;
    ImageFileName = open.FileName; 
}
// Open file dialog   
OpenFileDialog open = new OpenFileDialog();
// Image filters  
open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg;*.png;*.jpeg;*.gif;*.bmp";
if (open.ShowDialog() == DialogResult.OK) {  
    // Display image in PictureBox
    pictureBox1.Image = new Bitmap(open.FileName); 
    // Store image file path in class data member. Initialize it as string ImageFileName;
    ImageFileName = open.FileName; 
}
' Open file dialog   
Dim open As New OpenFileDialog()
' Image filters  
open.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg;*.png;*.jpeg;*.gif;*.bmp"
If open.ShowDialog() = DialogResult.OK Then
	' Display image in PictureBox
	pictureBox1.Image = New Bitmap(open.FileName)
	' Store image file path in class data member. Initialize it as string ImageFileName;
	ImageFileName = open.FileName
End If
$vbLabelText   $csharpLabel

The code for the "scan code" button:

// Read the barcode from the image file path
BarcodeResult Result = BarcodeReader.Read(ImageFileName);
// Display the decoded text in TextBox
textBox1.Text = Result.Text;
// Read the barcode from the image file path
BarcodeResult Result = BarcodeReader.Read(ImageFileName);
// Display the decoded text in TextBox
textBox1.Text = Result.Text;
' Read the barcode from the image file path
Dim Result As BarcodeResult = BarcodeReader.Read(ImageFileName)
' Display the decoded text in TextBox
textBox1.Text = Result.Text
$vbLabelText   $csharpLabel

The barcode scanner displays the barcode data in the text box as follows:

How to Use Barcode Scanners in C# Windows Application, Figure 2: Barcode Image to be Scanned with C# Barcode Image to be Scanned with C#

QR Code Scanner

In this section, the IronBarcode Library effectively handles real-world situations involving skewed QR codes. Although the skewed angle QR code can be handled and read by the Read method, it can nevertheless take more time to resolve. The IronBarcode library provides a customized way of using BarcodeReaderOptions as an extra parameter to deal with such image input. The code goes as follows:

// Define a collection of image filters to apply
var filtersToApply = new ImageFilterCollection() {
    new SharpenFilter(),
    new InvertFilter(),
    new ContrastFilter(),
    new BrightnessFilter(),
    new AdaptiveThresholdFilter(),
    new BinaryThresholdFilter()
};

// Configure barcode reader options with specified filters
BarcodeReaderOptions myOptionsExample = new BarcodeReaderOptions() {
    ImageFilters = filtersToApply,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
};

// Read the barcode/QR code with custom options and display result
BarcodeResult Result = BarcodeReader.Read(ImageFileName, myOptionsExample);
textBox1.Text = Result.Text;
// Define a collection of image filters to apply
var filtersToApply = new ImageFilterCollection() {
    new SharpenFilter(),
    new InvertFilter(),
    new ContrastFilter(),
    new BrightnessFilter(),
    new AdaptiveThresholdFilter(),
    new BinaryThresholdFilter()
};

// Configure barcode reader options with specified filters
BarcodeReaderOptions myOptionsExample = new BarcodeReaderOptions() {
    ImageFilters = filtersToApply,
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,
};

// Read the barcode/QR code with custom options and display result
BarcodeResult Result = BarcodeReader.Read(ImageFileName, myOptionsExample);
textBox1.Text = Result.Text;
' Define a collection of image filters to apply
Dim filtersToApply = New ImageFilterCollection() From {
	New SharpenFilter(),
	New InvertFilter(),
	New ContrastFilter(),
	New BrightnessFilter(),
	New AdaptiveThresholdFilter(),
	New BinaryThresholdFilter()
}

' Configure barcode reader options with specified filters
Dim myOptionsExample As New BarcodeReaderOptions() With {
	.ImageFilters = filtersToApply,
	.ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128
}

' Read the barcode/QR code with custom options and display result
Dim Result As BarcodeResult = BarcodeReader.Read(ImageFileName, myOptionsExample)
textBox1.Text = Result.Text
$vbLabelText   $csharpLabel

The output will be as follows after opening the skewed QR code image:

How to Use Barcode Scanners in C# Windows Application, Figure 4: Skewed QrCode Image Skewed QrCode Image

Reading Multiple Barcodes in a Single Scan

PDF Documents

Barcode images can be scanned from a PDF file, and each result can be displayed appropriately as desired. The following sample code allows you to read multiple barcodes from a PDF file.

// Scan for multiple barcodes within a PDF document
BarcodeResult[] PDFResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");

// Work with the results found
foreach (var PageResult in PDFResults) { 
    string Value = PageResult.Value;
    int PageNum = PageResult.PageNumber;
    System.Drawing.Bitmap Img = PageResult.BarcodeImage;
    BarcodeEncoding BarcodeType = PageResult.BarcodeType;
    byte[] Binary = PageResult.BinaryValue;
    Console.WriteLine(PageResult.Value + " on page " + PageNum);
}
// Scan for multiple barcodes within a PDF document
BarcodeResult[] PDFResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");

// Work with the results found
foreach (var PageResult in PDFResults) { 
    string Value = PageResult.Value;
    int PageNum = PageResult.PageNumber;
    System.Drawing.Bitmap Img = PageResult.BarcodeImage;
    BarcodeEncoding BarcodeType = PageResult.BarcodeType;
    byte[] Binary = PageResult.BinaryValue;
    Console.WriteLine(PageResult.Value + " on page " + PageNum);
}
' Scan for multiple barcodes within a PDF document
Dim PDFResults() As BarcodeResult = BarcodeReader.ReadPdf("MultipleBarcodes.pdf")

' Work with the results found
For Each PageResult In PDFResults
	Dim Value As String = PageResult.Value
	Dim PageNum As Integer = PageResult.PageNumber
	Dim Img As System.Drawing.Bitmap = PageResult.BarcodeImage
	Dim BarcodeType As BarcodeEncoding = PageResult.BarcodeType
	Dim Binary() As Byte = PageResult.BinaryValue
	Console.WriteLine(PageResult.Value & " on page " & PageNum)
Next PageResult
$vbLabelText   $csharpLabel

Barcode and QR code present in PDF files:

How to Use Barcode Scanners in C# Windows Application, Figure 3: C# - Reading Barcodes from a PDF results C# - Reading Barcodes from a PDF results

Reading Barcodes from Imperfect Images

In real-world use cases, barcodes are often found with imperfections in images, scans, thumbnails, or photographs, and may contain digital noise or be skewed. This section demonstrates how to read barcode data from thumbnails.

Thumbnails

The IronBarcode Library uses the C# Barcode Generator, which is even capable of reading a corrupted thumbnail of a barcode.

How to Use Barcode Scanners in C# Windows Application, Figure 5: Automatic barcode thumbnail size correction. File readable using IronBarcode in C# Automatic barcode thumbnail size correction. File readable using IronBarcode in C#

It automatically detects barcode images that are too small to reasonably represent an actual barcode, and then upscales and cleans all of the digital noise associated with thumbnailing, thereby allowing them to be readable again.

// Small or 'Thumbnail' barcode images are automatically detected by IronBarCode and corrected for wherever possible even if they have much digital noise.
BarcodeResult SmallResult = BarcodeReader.Read("ThumbnailOfBarcode.gif");
// Small or 'Thumbnail' barcode images are automatically detected by IronBarCode and corrected for wherever possible even if they have much digital noise.
BarcodeResult SmallResult = BarcodeReader.Read("ThumbnailOfBarcode.gif");
' Small or 'Thumbnail' barcode images are automatically detected by IronBarCode and corrected for wherever possible even if they have much digital noise.
Dim SmallResult As BarcodeResult = BarcodeReader.Read("ThumbnailOfBarcode.gif")
$vbLabelText   $csharpLabel

Summary

IronBarcode is a versatile .NET software library and C# QR Code Generator for scanning and reading a wide range of barcode image formats, and it can do so whether or not these barcodes are perfect screen grabs or are in fact photographs, scans, or other imperfect real-world images. 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. Visit the official documents page for more information about IronBarcode.

Currently, if you buy the complete Iron Suite, you can get five libraries for the price of just two.

Preguntas Frecuentes

¿Qué es un escáner de código de barras en el contexto de aplicaciones C#?

Un escáner de código de barras es un dispositivo que lee códigos de barras impresos, decodifica la información y la envía a una computadora. En aplicaciones C#, esta funcionalidad puede implementarse utilizando bibliotecas como IronBarcode.

¿Cómo puedo crear una aplicación de formularios de Windows para el escaneo de códigos de barras usando C#?

Para crear una aplicación de formularios de Windows para escanear códigos de barras en C#, abra Visual Studio, cree un nuevo proyecto utilizando la 'Plantilla de aplicación de formularios de Windows', configure su .NET Framework objetivo, y utilice controles como PictureBox, Label, TextBox y Button para diseñar el formulario.

¿Cuál es el método recomendado para instalar una biblioteca de código de barras en un proyecto C#?

Puede instalar una biblioteca de código de barras como IronBarcode en un proyecto C# a través del Consola del Administrador de Paquetes con Install-Package IronBarCode, a través del Administrador de Paquetes NuGet, o descargando el DLL y agregándolo como referencia.

¿Es posible leer múltiples códigos de barras en un escaneo usando una biblioteca C#?

Sí, usando IronBarcode, puede leer múltiples códigos de barras en un solo escaneo con el método BarcodeReader.ReadPdf, incluso desde documentos PDF.

¿Cómo gestiona la biblioteca la lectura de códigos de barras desde imágenes de baja calidad?

IronBarcode puede interpretar códigos de barras desde imágenes de baja calidad aplicando filtros de imagen y técnicas de escalado para reducir el ruido digital, garantizando lecturas precisas.

¿Qué formatos de códigos de barras son compatibles con bibliotecas C# como IronBarcode?

IronBarcode soporta una amplia gama de formatos de códigos de barras, incluidos códigos QR y Code128. Puede leer estos formatos incluso si las imágenes son imperfectas o se capturan con una cámara.

¿Cuáles son los pasos para implementar la lectura de códigos de barras en una aplicación .NET?

Para implementar la lectura de códigos de barras, cargue una imagen en un PictureBox, active la acción de 'escanear código' y use IronBarcode para procesar y mostrar el texto descodificado en un TextBox.

¿Puede IronBarcode manejar códigos QR sesgados o inclinados de manera efectiva?

Sí, IronBarcode puede manejar efectivamente códigos QR sesgados utilizando BarcodeReaderOptions para aplicar los filtros de imagen necesarios y ajustes para una lectura precisa.

¿Qué características de personalización ofrece IronBarcode para la lectura de códigos de barras?

IronBarcode ofrece características como regiones de recorte, multi-threading y ajustes de parámetros para mejorar la velocidad y precisión de la lectura de códigos de barras.

¿Dónde puedo encontrar más información detallada sobre el uso de bibliotecas de códigos de barras en C#?

Para obtener más información detallada sobre el uso de bibliotecas de códigos de barras en C#, puede visitar la página de documentación oficial 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