Cómo leer códigos de barras de imágenes en C#

How to Read Barcodes From Image Files (JPEG, PNG, GIF, TIFF, SVG, BMP)

This article was translated from English: Does it need improvement?
Translated
View the article in English

One of the key features of IronBarcode is its ability to read barcodes out-of-the-box in multiple image formats. The following image formats are currently supported by IronBarcode:

  • Scalable Vector Graphics (SVG)
  • Joint Photographic Experts Group (JPEG)
  • Portable Network Graphics (PNG)
  • Graphics Interchange Format (GIF)
  • Tagged Image File Format (TIFF)
  • Bitmap Image File (BMP)

This is made possible with the help of our open source library, IronDrawing.

Quickstart: Read Barcodes from an Image in Seconds

With just one simple call to IronBarCode.BarcodeReader.Read(), you can extract barcode data straight from image file formats like PNG, JPEG, GIF, BMP, and TIFF. Get started instantly—no complex setup, just instant results.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. Copy and run this code snippet.

    var results = IronBarCode.BarcodeReader.Read("path/to/image.png");
  3. Deploy to test on your live environment

    Start using IronBarcode in your project today with a free trial
    arrow pointer

Read Barcodes Directly From Images

Now, let us see how we can actually use IronBarcode for barcode reading:

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-images-1.cs
using IronBarCode;
using System;

var myBarcode = BarcodeReader.Read(@"image_file_path.jpg"); //image file path

foreach (var item in myBarcode)
{
    Console.WriteLine(item.ToString());
}
Imports IronBarCode
Imports System

Private myBarcode = BarcodeReader.Read("image_file_path.jpg") 'image file path

For Each item In myBarcode
	Console.WriteLine(item.ToString())
Next item
$vbLabelText   $csharpLabel
QRcodeintro related to Read Barcodes Directly From Images
Sample test QR code
Code128intro related to Read Barcodes Directly From Images
Sample test barcode

Want to know what are the barcode values in the samples? Try it with the code snippet!

To use IronBarcode, the first thing you have to do is to install the IronBarcode library via Microsoft Visual Studio NuGet package manager into your project, as shown in the picture below. This will allow you to access IronBarcode's BarcodeReader.Read() method to directly read barcode images.

IronBarcode offers simplicity by allowing users to only use BarcodeReader.Read() to read an image file that has already been included inside the project by specifying the file name string, OR file path string as the parameter for the method. Best practice is to use the verbatim string literal, "@" when specifying a file path in the method to avoid adding multiple escape characters "\" in the file path string.

Attach the Values() method at the end of the BarcodeReader.Read() method call to get the barcode value as a System.String[] object.

To output the result to the console, you can use a foreach loop to iterate over the values stored in the string[] array and inside the loop block, call the Console.WriteLine() method with the iterator variable as the parameter.

IronBarcode is capable of reading 1-Dimensional barcode formats (Codabar, Code128, Code39, Code93, EAN13, EAN18, ITF, MSI, UPCA, UPCE) as well as 2-Dimensional barcode formats (Aztec, DataMatrix, QRCode) in various image formats.

Setting Barcode Reader Options

Finding barcode reading too slow? Is the barcode too small in the picture, making IronBarcode unable to read it? Want to read only certain areas of an image? Want to read only certain types of barcodes in an image with a mixture of barcodes? Want to improve overall reading performance? Worry no more!

BarcodeReaderOptions allows users to tweak or adjust the behavior of the barcode reader so that it can address all the issues stated above. Let us see and discuss in detail all the adjustable properties available in BarcodeReaderOptions one-by-one.

CropArea

CropArea is a property of type IronSoftware.Drawing.CropRectangle available in BarcodeReaderOptions that allows users to specify the area in an image IronBarcode should read. This helps improve reading performance, since the barcode reader does not scan through the entire image for barcodes, as well as improving reading accuracy since the area of read has been specified.

To set the CropArea property, simply instantiate a new Rectangle type object and specify the rectangle coordinates, width, and length of the rectangle as arguments. The measurement unit accepted is pixels(px).

// Example of setting CropArea
var cropArea = new IronSoftware.Drawing.Rectangle(x, y, width, height);
// Example of setting CropArea
var cropArea = new IronSoftware.Drawing.Rectangle(x, y, width, height);
' Example of setting CropArea
Dim cropArea = New IronSoftware.Drawing.Rectangle(x, y, width, height)
$vbLabelText   $csharpLabel

ExpectBarcodeTypes

By default, all supported barcodes in IronBarcode will be scanned in an image. However, if the user knows what types of barcodes are available or want to be read in an image, setting this property to read only certain types of barcodes will greatly increase reading performance and accuracy since the barcode reader does not need to iterate through collections of barcodes to interpret and read a barcode.

To use this property, simply set the ExpectBarcodeTypes to one of the fields of the BarcodeEncoding enum. Below are examples of every barcode type supported by IronBarcode.

Here's a list of the barcode types with examples and explanations provided earlier.

ExpectMultipleBarcodes

IronBarcode will scan all barcodes available in an image by default, which includes scanning the whole image file and adding the read barcode values into the string array. However, if users do not wish to read multiple barcodes in an image file, users can set this property to false, which will make the barcode reader stop scanning once a barcode value has been found. This will again, improve the performance and reading speed of IronBarcode.

ImageFilters

One of the properties that can be added in BarcodeReaderOptions is a collection of image filters. Image filters are important for preprocessing the raw image fed to IronBarcode. To apply image filters inside the BarcodeReaderOptions, users must first initiate and specify the ImageFilter collection to be used.

MaxParallelThreads

IronBarcode allows users to enable and tweak the amount of parallel threads execution, which in turn will improve the speed and efficiency of the process. Parallel threads mean execution of multiple threads simultaneously on different processor cores. The default amount for the MaxParallelThread property in IronBarcode is 4. Users can adjust them based on the capabilities and amount of resources their machines have.

Multithreaded

This property enables IronBarcode to read multiple images in parallel. The default for Multithreaded is true, hence the multiple threads will be managed automatically to improve performance for batch barcode reading tasks.

RemoveFalsePositive

This property removes any false-positive barcode reads. False-positive barcode reads simply mean a false read of barcode values, but identified as valid. This can happen due to errors in the sequencing process or errors in the barcode labeling or preparation process. Therefore, setting RemoveFalsePositive as true will remove the false-positive barcode readings, thus improving barcode reading accuracy. However, if users opt for performance at the cost of accuracy, setting this property to false would help. The default value for this property is true.

ScanMode

Define how IronBarcode scans and detects barcodes in an image.

  • Auto: Reads barcodes with automatic image pre-processing and the most optimal reader options configured. Recommended for best results and performance.
  • OnlyDetectionModel: Scans the image for barcodes and returns their positions as an array of IronSoftware.Drawing.PointF. This mode does not read the detected barcodes; it only returns the positions of each barcode.
  • MachineLearningScan: Scans the image for barcodes with machine learning detection and reads them.
  • OnlyBasicScan: Reads barcodes without machine learning detection, automatic image pre-processing, or reader option configuration. This option can be used with IronBarCode.Slim alone.

Reading Speed

As the name suggests, the Speed property enables users to further optimize the performance of the IronBarcode reader. Similar to the RemoveFalsePositive property, adjusting this property improves performance at the cost of accuracy. It accepts the ReadingSpeed enum, which has 4 levels as shown below:

  • Faster: Enables the fastest barcode reading but reduces accuracy. The process skips image preprocessing, often resulting in empty barcode results. Use this setting only if the input image is sharp and clear.
  • Balanced: This setting is recommended for the Speed property. It sets a balance between accuracy and read performance by attempting to apply light processing to the image to clarify the barcode area and make it stand out for the barcode reader to detect. Most of the time, this setting is enough for IronBarcode to read a barcode image and produce accurate output.
  • Detailed: For cases where using the setting ReadingSpeed.Balanced is not successful in producing barcode values from the read, users may opt to use ReadingSpeed.Detailed. IronBarcode will perform medium processing on the image to clarify the barcode area further and clearer for the barcode reader to detect the barcode. This setting is very useful to detect a small or less sharp barcode image.
  • ExtremeDetail: This setting is the least recommended due to its CPU-intensive process. Heavy processing will be performed on the barcode image in order for the reader to read the barcodes. This will greatly reduce the reading performance of IronBarcode. Users are advised to do image preprocessing/applying filters on the image before opting for this setting.

UseCode39ExtendedMode

This setting allows Code39 type barcodes to be read and interpreted with extended mode whereby the full ASCII Character Set will be applied. Setting UseCode39ExtendedMode to true will enable a more accurate reading of Code39 barcodes.

Advance Barcode Read from Image

Now that we have learned all the options that can be tweaked by users, be it to increase performance or accuracy, let us see how we can apply it in our code. The code snippet below demonstrates.

// Insert actual C# code for advanced barcode reading from images here
// Ensure the necessary options and settings are demonstrated in the example
// Insert actual C# code for advanced barcode reading from images here
// Ensure the necessary options and settings are demonstrated in the example
' Insert actual C# code for advanced barcode reading from images here
' Ensure the necessary options and settings are demonstrated in the example
$vbLabelText   $csharpLabel

From the code snippet, we see that to use BarcodeReaderOptions we have to first initialize it, then determine and adjust the properties of the BarcodeReaderOptions according to the properties stated above. The initialized BarcodeReaderOptions can then be used as an argument in the BarcodeReader.Read() method along with the image file. This will apply all the settings in BarcodeReaderOptions when reading a barcode from the image.

Preguntas Frecuentes

¿Cómo puedo leer códigos de barras de imágenes en una aplicación .NET?

Puedes usar el método BarcodeReader.Read() de IronBarcode para leer códigos de barras de archivos de imagen como JPEG, PNG, GIF, TIFF, SVG y BMP.

¿Qué opciones están disponibles para personalizar la lectura de códigos de barras en IronBarcode?

La clase BarcodeReaderOptions permite la personalización de la lectura de códigos de barras configurando propiedades como CropArea, ExpectBarcodeTypes, ImageFilters, MaxParallelThreads y RemoveFalsePositive.

¿Cómo puedo mejorar la precisión de lectura de códigos de barras en mi aplicación?

Mejorar la precisión de lectura de códigos de barras se puede lograr utilizando la propiedad RemoveFalsePositive para eliminar falsos positivos y ajustando la velocidad de lectura con opciones como Detailed o ExtremeDetail.

¿Es posible realizar la lectura de códigos de barras en múltiples hilos en .NET?

Sí, IronBarcode soporta la lectura de códigos de barras en múltiples hilos. Puedes habilitar esto configurando la propiedad Multithreaded a true, lo que permite la gestión automática de hilos.

¿Cómo especifico una región de una imagen para escanear códigos de barras?

Puedes especificar una región dentro de una imagen para escanear configurando la propiedad CropArea en la clase BarcodeReaderOptions en IronBarcode.

¿Cuáles son los beneficios de usar el aprendizaje automático en la lectura de códigos de barras?

Usar aprendizaje automático para la detección de códigos de barras puede mejorar la precisión y eficiencia de la lectura al adaptarse a varias condiciones de imagen y mejorar las capacidades de reconocimiento en IronBarcode.

¿Cómo puedo manejar diferentes formatos de código de barras en IronBarcode?

IronBarcode es capaz de leer formatos de código de barras 1D y 2D. Puedes especificar los tipos de códigos de barras a esperar utilizando la propiedad ExpectBarcodeTypes.

¿Cuál es el proceso para instalar una biblioteca de lectura de códigos de barras en un proyecto .NET?

Para instalar la biblioteca IronBarcode en un proyecto .NET, usa el gestor de paquetes NuGet en Microsoft Visual Studio para descargar e integrar la biblioteca.

¿Qué opciones de preprocesamiento de imágenes están disponibles en IronBarcode?

IronBarcode proporciona opciones de preprocesamiento de imágenes a través de la propiedad ImageFilters, permitiendo a los usuarios mejorar las imágenes antes de leer los códigos de barras.

¿Cómo optimizo el rendimiento de lectura de códigos de barras para archivos de imagen grandes?

Optimiza el rendimiento configurando el MaxParallelThreads para utilizar múltiples hilos y ajustando la velocidad de lectura según tus necesidades.

Hairil Hasyimi Bin Omar
Ingeniero de Software
Como todos los grandes ingenieros, Hairil es un ávido aprendiz. Está refinando su conocimiento de C#, Python y Java, usando ese conocimiento para agregar valor a los miembros del equipo en Iron Software. Hairil se unió al equipo de Iron Software desde la Universiti Teknologi MARA en Malasia, donde se ...
Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado