Saltar al pie de página
COMPARAR CON OTROS COMPONENTES

Cómo Escanear Códigos de Barras en ZXing Para Desarrolladores en C#

Barcodes provide a clear and machine-readable way to present data. Initially, barcodes consisted of parallel lines with varying widths and spacing, serving as a representation of data. These traditional linear or one-dimensional (1D) barcodes could be scanned by specialized optical devices called barcode readers. However, the evolution of barcodes led to the invention of two-dimensional (2D) barcodes, also known as matrix codes. Unlike traditional barcodes, 2D barcodes utilize patterns such as rectangles, dots, and hexagons instead of bars. To read these 2D barcodes, specific optical scanner setups are available, or alternative methods involve using a digital camera connected to a computer running decoding software. Moreover, mobile devices like smartphones can leverage their integrated cameras and dedicated applications to function as a 2D barcode scanner.

ZXing Barcode Scanner

Zebra Crossing, often known as ZXing, is an open-source, multi-format 1D/2D barcode image processing toolkit that was developed in Java and has ports for other languages. The core image decoding library, Java-specific client code, and the Android client Barcode Scanner are only a few of the modules that make up ZXing. Numerous more independent open-source projects are built upon it.

1. Features

  • It can keep track of URLs, contact information, calendar events, and more.
  • It was created with Java SE applications in mind.
  • Through purpose, barcode scanner integration is possible.
  • It is a simple Google Glass application.

2. Using ZXing with .NET

Open Visual Studio, choose "new project" from the file menu, then "console application". In this article, we are choosing the C# console app.

How to Scan Barcodes in ZXing For C# Developers Figure 1

Enter the project name and the file path in the appropriate text box. Next, click the Create button to choose the required .NET Framework.

If you selected a console application, the project will now create its structure and open the program.cs file, allowing you to enter the program's code and build or execute it.

How to Scan Barcodes in ZXing For C# Developers Figure 2

2.1 Install ZXing Barcode

Enter the following command into the NuGet Package Manager Console to install the ZXing library:

Install-Package ZXing.Net.Bindings.Windows.Compatibility

Alternatively, you can get the package using the NuGet package manager tool. Like the illustration below. Try installing the first result you choose.

How to Scan Barcodes in ZXing For C# Developers Figure 3

2.2 Read and Write Barcode using ZXing

We can create a barcode using the following sample code. ZXing allows us to create more than 10 types of barcode formats.

using ZXing.Windows.Compatibility;

var options = new QrCodeEncodingOptions
{
    Width = 250,
    Height = 250,
};

var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = options;

// Encode the string into a QR code bitmap image
System.Drawing.Bitmap _bitmap = writer.Write("Hello world");

// Save the bitmap as a PNG file
_bitmap.Save("Demo1.png");
using ZXing.Windows.Compatibility;

var options = new QrCodeEncodingOptions
{
    Width = 250,
    Height = 250,
};

var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = options;

// Encode the string into a QR code bitmap image
System.Drawing.Bitmap _bitmap = writer.Write("Hello world");

// Save the bitmap as a PNG file
_bitmap.Save("Demo1.png");
Imports ZXing.Windows.Compatibility

Private options = New QrCodeEncodingOptions With {
	.Width = 250,
	.Height = 250
}

Private writer = New BarcodeWriter()
writer.Format = BarcodeFormat.QR_CODE
writer.Options = options

' Encode the string into a QR code bitmap image
Dim _bitmap As System.Drawing.Bitmap = writer.Write("Hello world")

' Save the bitmap as a PNG file
_bitmap.Save("Demo1.png")
$vbLabelText   $csharpLabel

The code above sets the height and width for the QrCodeEncodingOptions. Then it creates an instance of BarcodeWriter. For the BarcodeWriter, we set the barcode format as QR code. We assign the previously created QR code options to the writer. The Write method in the BarcodeWriter encodes the given string into a barcode and returns it as a bitmap image. The image is saved using the Save method of the bitmap. Below is the result from the code.

How to Scan Barcodes in ZXing For C# Developers Figure 4

The next code sample demonstrates decoding a barcode using ZXing.

using ZXing.Windows.Compatibility;

// Load the barcode image into a bitmap
var barcodeBitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile("demo.png");

// Create a BarcodeReader object
var reader = new BarcodeReader();

// Decode the bitmap into a result
var result = reader.Decode(barcodeBitmap);

if (result != null)
{
    // Output the decoded text to the console
    Console.WriteLine(result.Text);
    Console.ReadKey();
}
using ZXing.Windows.Compatibility;

// Load the barcode image into a bitmap
var barcodeBitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile("demo.png");

// Create a BarcodeReader object
var reader = new BarcodeReader();

// Decode the bitmap into a result
var result = reader.Decode(barcodeBitmap);

if (result != null)
{
    // Output the decoded text to the console
    Console.WriteLine(result.Text);
    Console.ReadKey();
}
Imports ZXing.Windows.Compatibility

' Load the barcode image into a bitmap
Private barcodeBitmap = CType(System.Drawing.Bitmap.FromFile("demo.png"), System.Drawing.Bitmap)

' Create a BarcodeReader object
Private reader = New BarcodeReader()

' Decode the bitmap into a result
Private result = reader.Decode(barcodeBitmap)

If result IsNot Nothing Then
	' Output the decoded text to the console
	Console.WriteLine(result.Text)
	Console.ReadKey()
End If
$vbLabelText   $csharpLabel

In the code above, we first load the image into a bitmap and then create a BarcodeReader object. The Decode function allows us to pass the bitmap as a parameter, which can return results in multiple formats. We use the Text property to get the text encoded in the barcode.

How to Scan Barcodes in ZXing For C# Developers Figure 5

IronBarcode

With the help of this barcode library, reading and creating barcodes is straightforward. A dynamic barcode is easy to make with IronBarcode's Library. With just a few lines of code, this simple library can generate a barcode, which helps us to encode barcode images. IronBarcode enables us to generate barcodes in languages like C# and VB.NET.

1. Features

  • IronBarcode can read and write the majority of barcode image formats and QR standards, including UPC A/E, Databar, EAN 8/13, MSI, Code 39/93/128, CodaB, RSS 14/Expanded, and ITF.
  • While scanning scans and real-time video frames, IronBarcode can rectify rotation, noise, distortion, and skewing. To improve reading accuracy and speed, IronBarcode preprocesses barcode images automatically as they are being created. Dynamic barcodes are frequently used as they allow for changing content.
  • IronBarcode's ability to utilize many cores and threads is advantageous for batch-processing servers.
  • In single- and multipage documents, IronBarcode can automatically find one or more barcodes.

2. Using IronBarcode

To utilize the IronBarcode library in the solution, you must download the required package. To do this, use the following command in the NuGet Package Manager Console:

Install-Package BarCode

As an alternative, you can use the NuGet Package Manager, which will show all the search results, to seek and download the "Barcode" package. Then you can select the essential package to download into the program from them.

How to Scan Barcodes in ZXing For C# Developers Figure 6

3. Read and Write Barcodes using IronBarcode

With just a few lines of code, we can quickly make barcode images using the IronBarcode library. Additionally, it enables us to save the created barcode as a separate picture file. Here is some sample C# code for creating a barcode label with a Console program.

using IronBarCode;

// Create a QR code with a medium error correction level
QRCodeWriter.CreateQrCode("Your text here", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("demo.png");
using IronBarCode;

// Create a QR code with a medium error correction level
QRCodeWriter.CreateQrCode("Your text here", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("demo.png");
Imports IronBarCode

' Create a QR code with a medium error correction level
QRCodeWriter.CreateQrCode("Your text here", 500, QRCodeWriter.QrErrorCorrectionLevel.Medium).SaveAsPng("demo.png")
$vbLabelText   $csharpLabel

This code produces a 500 by 500 pixel graphic using a medium level of error correction, and then saves it to a file location using the SaveAsPng method.

The next code example reads the text encoded in the QR code that we created in the previous example.

using IronBarCode;

// Load the QR code image into a bitmap
var barcodeBitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile("demo.png");

// Read the barcode image
var reader = IronBarCode.BarcodeReader.Read(barcodeBitmap);

// Output the decoded value to the console
Console.WriteLine(reader.Values[0]);
Console.ReadKey();
using IronBarCode;

// Load the QR code image into a bitmap
var barcodeBitmap = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile("demo.png");

// Read the barcode image
var reader = IronBarCode.BarcodeReader.Read(barcodeBitmap);

// Output the decoded value to the console
Console.WriteLine(reader.Values[0]);
Console.ReadKey();
Imports IronBarCode

' Load the QR code image into a bitmap
Private barcodeBitmap = CType(System.Drawing.Bitmap.FromFile("demo.png"), System.Drawing.Bitmap)

' Read the barcode image
Private reader = IronBarCode.BarcodeReader.Read(barcodeBitmap)

' Output the decoded value to the console
Console.WriteLine(reader.Values(0))
Console.ReadKey()
$vbLabelText   $csharpLabel

We first load the image into a bitmap, and then read the image using the Read method on the BarcodeReader class. We use the Values property on the BarcodeResults object returned from the Read method to get the content that was read from the QR code.

To know more about ZXing and how it compares with IronBarcode, read this next blog post.

Our Reading Barcodes tutorial also provides more information about how to use IronBarcode to read barcodes and QR codes. For more code tutorials on IronBarcode.

Conclusion

ZXing barcode scanner can create high-quality barcodes, but it is outdated and supports few barcode formats. It also has limited documentation and product support.

On the other hand, IronBarcode is very efficient and flexible, and is able to work on many operating systems. IronBarcode can change the color, size, spacing, and lettering used in barcodes. It also supports Crystal Reports.

Developers can use IronBarcode for free. Users can purchase a license to access additional features and receive a full year of support and product updates.

Por favor notaZXing is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by ZXing. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

Preguntas Frecuentes

¿Cómo puedo convertir HTML a PDF en C#?

Puedes usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas de HTML en PDFs. También puedes convertir archivos HTML a PDFs usando RenderHtmlFileAsPdf.

¿Cuáles son las diferencias entre IronBarcode y ZXing?

IronBarcode ofrece mayor flexibilidad y admite una gama más amplia de formatos de códigos de barras en comparación con ZXing. Aunque ZXing es efectivo para crear códigos de barras, su soporte de formatos y documentación son limitados. IronBarcode sobresale en eficiencia y es compatible con varios sistemas operativos.

¿Cómo escanear un código de barras usando un dispositivo móvil?

Con el cliente Android de ZXing, Barcode Scanner, puedes usar la cámara de tu dispositivo para escanear códigos de barras. Para características más robustas, IronBarcode se puede integrar en aplicaciones móviles para mejorar las capacidades de escaneo de códigos de barras.

¿IronBarcode soporta códigos de barras 2D?

Sí, IronBarcode soporta tanto códigos de barras 1D como 2D, incluidos códigos QR, permitiendo una versátil lectura y creación de códigos de barras.

¿Puede IronBarcode gestionar la creación dinámica de códigos de barras?

IronBarcode soporta la creación dinámica de códigos de barras, permitiéndote personalizar los códigos en términos de color, tamaño, espaciado y rotulación para cumplir con requisitos específicos.

¿Qué se requiere para integrar IronBarcode en un proyecto .NET?

Para integrar IronBarcode en un proyecto .NET, instala el paquete a través de la Consola del Gestor de Paquetes NuGet usando Install-Package IronBarcode o encuéntralo en el Gestor de Paquetes NuGet.

¿Hay un costo asociado con el uso de IronBarcode?

IronBarcode ofrece una prueba gratuita, pero comprar una licencia proporciona características adicionales, actualizaciones de producto y un año de soporte.

¿Se puede utilizar IronBarcode para leer códigos de barras desde fotogramas de video?

Sí, IronBarcode puede procesar fotogramas de video en tiempo real, corrigiendo rotación, ruido, distorsión e inclinación para mejorar la precisión y velocidad en el escaneo de códigos de barras.

¿Cuáles son las características de ZXing para el escaneo de códigos de barras?

ZXing proporciona un conjunto de herramientas de código abierto para el escaneo de códigos de barras, en particular para códigos de barras 1D y 2D. Incluye una biblioteca principal de decodificación de imágenes y un cliente Android Barcode Scanner.

¿Qué lenguajes de programación son compatibles con IronBarcode?

IronBarcode soporta C# y VB.NET, lo que lo hace ideal para desarrolladores que trabajan dentro del marco de .NET.

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