Cómo Leer Códigos de Barras en C#

C# Barcode Scanner: Read Barcodes & QR Codes in .NET Applications

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

Need to quickly scan barcodes or QR codes in your .NET application? IronBarcode makes barcode reading simple and reliable, whether you're processing perfect digital images or challenging real-world photos. This guide shows you exactly how to implement barcode scanning in C# with practical examples you can use immediately.

Quickstart: Read a Barcode from a File Instantly

This quick example shows you how easy it is to get started with IronBarcode. In just one line of code, you can read barcodes from an image file—no complex setup required.

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/barcode.png");
  3. Deploy to test on your live environment

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

How do I install IronBarcode in my .NET project?

IronBarcode installs easily through NuGet Package Manager or by downloading the DLL directly. The NuGet installation is the recommended approach as it automatically manages dependencies and updates.

Comience a usar IronBarcode en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer

Install-Package BarCode

After installation, add using IronBarCode; to your C# files to access the barcode scanning functionality. For detailed installation instructions across different development environments, check our installation guide.

How can I read my first barcode using C#?

Reading barcodes with IronBarcode requires just one line of code. The library automatically detects barcode formats and extracts all encoded data.

Code128 barcode ready for scanning - contains text 'https://ironsoftware.com/csharp/barcode/' A standard Code128 barcode that IronBarcode can read instantly
using IronBarCode;
using System;

// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");

// Check if any barcodes were detected
if (results != null && results.Count > 0)
{
    // Process each barcode found in the image
    foreach (BarcodeResult result in results)
    {
        // Extract the text value from the barcode
        Console.WriteLine("Barcode detected! Value: " + result.Text);

        // Additional properties available:
        // result.BarcodeType - The format (Code128, QR, etc.)
        // result.BinaryValue - Raw binary data if applicable
        // result.Confidence - Detection confidence score
    }
}
else
{
    Console.WriteLine("No barcodes detected in the image.");
}
using IronBarCode;
using System;

// Read barcodes from the image file - supports PNG, JPG, BMP, GIF, and more
BarcodeResults results = BarcodeReader.Read("GetStarted.png");

// Check if any barcodes were detected
if (results != null && results.Count > 0)
{
    // Process each barcode found in the image
    foreach (BarcodeResult result in results)
    {
        // Extract the text value from the barcode
        Console.WriteLine("Barcode detected! Value: " + result.Text);

        // Additional properties available:
        // result.BarcodeType - The format (Code128, QR, etc.)
        // result.BinaryValue - Raw binary data if applicable
        // result.Confidence - Detection confidence score
    }
}
else
{
    Console.WriteLine("No barcodes detected in the image.");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The BarcodeReader.Read method returns a BarcodeResults collection containing all detected barcodes. Each BarcodeResult provides access to the barcode's text value, format type, position coordinates, and binary data. This approach works seamlessly with common barcode formats including Code128, Code39, QR codes, and Data Matrix codes.

What options help read challenging or damaged barcodes?

Real-world barcode scanning often involves imperfect images - skewed angles, poor lighting, or partial damage. IronBarcode's advanced options handle these challenges effectively.

using IronBarCode;

// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Speed settings: Faster, Balanced, Detailed, ExtremeDetail
    // ExtremeDetail performs deep analysis for challenging images
    Speed = ReadingSpeed.ExtremeDetail,

    // Specify expected formats to improve performance
    // Use bitwise OR (|) to combine multiple formats
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,

    // Maximum number of barcodes to find (0 = unlimited)
    MaxParallelThreads = 4,

    // Crop region for faster processing of specific areas
    CropArea = null // Or specify a Rectangle
};

// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

// Process detected barcodes
foreach (var barcode in results)
{
    Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
using IronBarCode;

// Configure advanced reading options for difficult barcodes
BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Speed settings: Faster, Balanced, Detailed, ExtremeDetail
    // ExtremeDetail performs deep analysis for challenging images
    Speed = ReadingSpeed.ExtremeDetail,

    // Specify expected formats to improve performance
    // Use bitwise OR (|) to combine multiple formats
    ExpectBarcodeTypes = BarcodeEncoding.QRCode | BarcodeEncoding.Code128,

    // Maximum number of barcodes to find (0 = unlimited)
    MaxParallelThreads = 4,

    // Crop region for faster processing of specific areas
    CropArea = null // Or specify a Rectangle
};

// Apply options when reading
BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

// Process detected barcodes
foreach (var barcode in results)
{
    Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}");
}
Imports IronBarCode

' Configure advanced reading options for difficult barcodes
Private options As New BarcodeReaderOptions With {
	.Speed = ReadingSpeed.ExtremeDetail,
	.ExpectBarcodeTypes = BarcodeEncoding.QRCode Or BarcodeEncoding.Code128,
	.MaxParallelThreads = 4,
	.CropArea = Nothing
}

' Apply options when reading
Private results As BarcodeResults = BarcodeReader.Read("TryHarderQR.png", options)

' Process detected barcodes
For Each barcode In results
	Console.WriteLine($"Format: {barcode.BarcodeType}, Value: {barcode.Text}")
Next barcode
$vbLabelText   $csharpLabel
QR code rotated 45 degrees demonstrating IronBarcode's rotation handling A rotated QR code that IronBarcode successfully reads using advanced options

The ExpectBarcodeTypes property significantly improves performance by limiting the search to specific formats. For maximum accuracy with problematic images, combine image filters with automatic rotation:

using IronBarCode;

BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Apply image processing filters to enhance readability
    ImageFilters = new ImageFilterCollection
    {
        new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
        new ContrastFilter(2.0f),               // Increases contrast
        new SharpenFilter()                     // Reduces blur
    },

    // Automatically rotate to find barcodes at any angle
    AutoRotate = true,

    // Use multiple CPU cores for faster processing
    Multithreaded = true
};

BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

foreach (var result in results)
{
    Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
    Console.WriteLine($"Confidence: {result.Confidence}%");
    Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
using IronBarCode;

BarcodeReaderOptions options = new BarcodeReaderOptions
{
    // Apply image processing filters to enhance readability
    ImageFilters = new ImageFilterCollection
    {
        new AdaptiveThresholdFilter(9, 0.01f), // Handles varying lighting
        new ContrastFilter(2.0f),               // Increases contrast
        new SharpenFilter()                     // Reduces blur
    },

    // Automatically rotate to find barcodes at any angle
    AutoRotate = true,

    // Use multiple CPU cores for faster processing
    Multithreaded = true
};

BarcodeResults results = BarcodeReader.Read("TryHarderQR.png", options);

foreach (var result in results)
{
    Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}");
    Console.WriteLine($"Confidence: {result.Confidence}%");
    Console.WriteLine($"Position: X={result.X}, Y={result.Y}");
}
Imports IronBarCode

Private options As New BarcodeReaderOptions With {
	.ImageFilters = New ImageFilterCollection From {
		New AdaptiveThresholdFilter(9, 0.01F),
		New ContrastFilter(2.0F),
		New SharpenFilter()
	},
	.AutoRotate = True,
	.Multithreaded = True
}

Private results As BarcodeResults = BarcodeReader.Read("TryHarderQR.png", options)

For Each result In results
	Console.WriteLine($"Detected {result.BarcodeType}: {result.Text}")
	Console.WriteLine($"Confidence: {result.Confidence}%")
	Console.WriteLine($"Position: X={result.X}, Y={result.Y}")
Next result
$vbLabelText   $csharpLabel

These advanced features make IronBarcode ideal for scanning barcodes from photos, security cameras, or mobile device captures where image quality varies significantly.

How do I scan multiple barcodes from PDF documents?

PDF barcode scanning is essential for processing invoices, shipping labels, and inventory documents. IronBarcode reads all barcodes across every page efficiently.

Reading barcodes from PDF files

using System;
using IronBarCode;

try
{
    // Scan all pages of a PDF for barcodes
    BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");

    if (results != null && results.Count > 0)
    {
        foreach (var barcode in results)
        {
            // Access barcode data and metadata
            string value = barcode.Text;
            int pageNumber = barcode.PageNumber;
            BarcodeEncoding format = barcode.BarcodeType;
            byte[] binaryData = barcode.BinaryValue;

            // Extract barcode image if needed
            System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;

            Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
        }
    }
    else
    {
        Console.WriteLine("No barcodes found in the PDF.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading PDF: {ex.Message}");
}
using System;
using IronBarCode;

try
{
    // Scan all pages of a PDF for barcodes
    BarcodeResults results = BarcodeReader.ReadPdf("MultipleBarcodes.pdf");

    if (results != null && results.Count > 0)
    {
        foreach (var barcode in results)
        {
            // Access barcode data and metadata
            string value = barcode.Text;
            int pageNumber = barcode.PageNumber;
            BarcodeEncoding format = barcode.BarcodeType;
            byte[] binaryData = barcode.BinaryValue;

            // Extract barcode image if needed
            System.Drawing.Bitmap barcodeImage = barcode.BarcodeImage;

            Console.WriteLine($"Found {format} on page {pageNumber}: {value}");
        }
    }
    else
    {
        Console.WriteLine("No barcodes found in the PDF.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error reading PDF: {ex.Message}");
}
Imports System
Imports IronBarCode

Try
	' Scan all pages of a PDF for barcodes
	Dim results As BarcodeResults = BarcodeReader.ReadPdf("MultipleBarcodes.pdf")

	If results IsNot Nothing AndAlso results.Count > 0 Then
		For Each barcode In results
			' Access barcode data and metadata
			Dim value As String = barcode.Text
			Dim pageNumber As Integer = barcode.PageNumber
			Dim format As BarcodeEncoding = barcode.BarcodeType
			Dim binaryData() As Byte = barcode.BinaryValue

			' Extract barcode image if needed
			Dim barcodeImage As System.Drawing.Bitmap = barcode.BarcodeImage

			Console.WriteLine($"Found {format} on page {pageNumber}: {value}")
		Next barcode
	Else
		Console.WriteLine("No barcodes found in the PDF.")
	End If
Catch ex As Exception
	Console.WriteLine($"Error reading PDF: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

Multiple barcodes detected across PDF pages showing console output Console output showing multiple barcodes found across different PDF pages

For specific page ranges or advanced PDF processing, use BarcodeReaderOptions:

// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
    // Scan pages 1-5 only
    PageNumbers = new[] { 1, 2, 3, 4, 5 },

    // PDF-specific settings
    PdfDpi = 300, // Higher DPI for better accuracy
    ReadBehindVectorGraphics = true
};

BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
// Read only specific pages to improve performance
BarcodeReaderOptions pdfOptions = new BarcodeReaderOptions
{
    // Scan pages 1-5 only
    PageNumbers = new[] { 1, 2, 3, 4, 5 },

    // PDF-specific settings
    PdfDpi = 300, // Higher DPI for better accuracy
    ReadBehindVectorGraphics = true
};

BarcodeResults results = BarcodeReader.ReadPdf("document.pdf", pdfOptions);
' Read only specific pages to improve performance
Dim pdfOptions As New BarcodeReaderOptions With {
	.PageNumbers = { 1, 2, 3, 4, 5 },
	.PdfDpi = 300,
	.ReadBehindVectorGraphics = True
}

Dim results As BarcodeResults = BarcodeReader.ReadPdf("document.pdf", pdfOptions)
$vbLabelText   $csharpLabel

Learn more about PDF barcode extraction techniques in our detailed examples.

How can I process multiframe TIFF images?

Multiframe TIFF files, common in document scanning and fax systems, receive the same comprehensive support as PDFs.

Multiframe TIFF containing multiple barcodes across frames A multiframe TIFF file with barcodes on different frames

using IronBarCode;

// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");

foreach (var result in multiFrameResults)
{
    // Access frame-specific information
    int frameNumber = result.PageNumber; // Frame number in TIFF
    string barcodeValue = result.Text;

    Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");

    // Save individual barcode images if needed
    result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
using IronBarCode;

// TIFF files are processed similarly to regular images
// Each frame is scanned automatically
BarcodeResults multiFrameResults = BarcodeReader.Read("Multiframe.tiff");

foreach (var result in multiFrameResults)
{
    // Access frame-specific information
    int frameNumber = result.PageNumber; // Frame number in TIFF
    string barcodeValue = result.Text;

    Console.WriteLine($"Frame {frameNumber}: {barcodeValue}");

    // Save individual barcode images if needed
    result.BarcodeImage?.Save($"barcode_frame_{frameNumber}.png");
}
Imports IronBarCode

' TIFF files are processed similarly to regular images
' Each frame is scanned automatically
Private multiFrameResults As BarcodeResults = BarcodeReader.Read("Multiframe.tiff")

For Each result In multiFrameResults
	' Access frame-specific information
	Dim frameNumber As Integer = result.PageNumber ' Frame number in TIFF
	Dim barcodeValue As String = result.Text

	Console.WriteLine($"Frame {frameNumber}: {barcodeValue}")

	' Save individual barcode images if needed
	If result.BarcodeImage IsNot Nothing Then
		result.BarcodeImage.Save($"barcode_frame_{frameNumber}.png")
	End If
Next result
$vbLabelText   $csharpLabel

The same BarcodeReaderOptions apply to TIFF processing, including image filters and rotation settings. For detailed TIFF handling scenarios, see our image processing tutorials.

Can I speed up processing with multithreading?

Processing multiple documents benefits dramatically from parallel processing. IronBarcode automatically utilizes available CPU cores for optimal performance.

using IronBarCode;

// List of documents to process - mix of formats supported
var documentBatch = new[] 
{ 
    "invoice1.pdf", 
    "shipping_label.png", 
    "inventory_sheet.tiff",
    "product_catalog.pdf"
};

// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
    // Enable parallel processing across documents
    Multithreaded = true,

    // Limit threads if needed (0 = use all cores)
    MaxParallelThreads = Environment.ProcessorCount,

    // Apply consistent settings to all documents
    Speed = ReadingSpeed.Balanced,
    ExpectBarcodeTypes = BarcodeEncoding.All
};

// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);

// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);

foreach (var docGroup in resultsByDocument)
{
    Console.WriteLine($"\nDocument: {docGroup.Key}");
    foreach (var barcode in docGroup)
    {
        Console.WriteLine($"  - {barcode.BarcodeType}: {barcode.Text}");
    }
}
using IronBarCode;

// List of documents to process - mix of formats supported
var documentBatch = new[] 
{ 
    "invoice1.pdf", 
    "shipping_label.png", 
    "inventory_sheet.tiff",
    "product_catalog.pdf"
};

// Configure for batch processing
BarcodeReaderOptions batchOptions = new BarcodeReaderOptions
{
    // Enable parallel processing across documents
    Multithreaded = true,

    // Limit threads if needed (0 = use all cores)
    MaxParallelThreads = Environment.ProcessorCount,

    // Apply consistent settings to all documents
    Speed = ReadingSpeed.Balanced,
    ExpectBarcodeTypes = BarcodeEncoding.All
};

// Process all documents in parallel
BarcodeResults batchResults = BarcodeReader.Read(documentBatch, batchOptions);

// Group results by source document
var resultsByDocument = batchResults.GroupBy(r => r.Filename);

foreach (var docGroup in resultsByDocument)
{
    Console.WriteLine($"\nDocument: {docGroup.Key}");
    foreach (var barcode in docGroup)
    {
        Console.WriteLine($"  - {barcode.BarcodeType}: {barcode.Text}");
    }
}
Imports Microsoft.VisualBasic
Imports IronBarCode

' List of documents to process - mix of formats supported
Private documentBatch = { "invoice1.pdf", "shipping_label.png", "inventory_sheet.tiff", "product_catalog.pdf" }

' Configure for batch processing
Private batchOptions As New BarcodeReaderOptions With {
	.Multithreaded = True,
	.MaxParallelThreads = Environment.ProcessorCount,
	.Speed = ReadingSpeed.Balanced,
	.ExpectBarcodeTypes = BarcodeEncoding.All
}

' Process all documents in parallel
Private batchResults As BarcodeResults = BarcodeReader.Read(documentBatch, batchOptions)

' Group results by source document
Private resultsByDocument = batchResults.GroupBy(Function(r) r.Filename)

For Each docGroup In resultsByDocument
	Console.WriteLine($vbLf & "Document: {docGroup.Key}")
	For Each barcode In docGroup
		Console.WriteLine($"  - {barcode.BarcodeType}: {barcode.Text}")
	Next barcode
Next docGroup
$vbLabelText   $csharpLabel

This parallel approach processes documents simultaneously, reducing total scanning time by up to 75% on multicore systems. For enterprise-scale barcode processing, explore our performance optimization guide.

Summary

IronBarcode transforms complex barcode scanning into straightforward C# code. Whether you're building inventory systems, document processors, or mobile applications, the library handles everything from pristine digital barcodes to challenging real-world captures.

Key capabilities covered:

  • Single-line barcode reading from images
  • Advanced options for damaged or rotated barcodes
  • Comprehensive PDF and TIFF document scanning
  • High-performance batch processing with multithreading
  • Support for all major barcode formats

Further Reading

Expand your barcode processing capabilities with these resources:

Source Code Downloads

Run these examples yourself:

Ready to implement barcode scanning in your application? Start your free trial and add professional barcode reading to your .NET project today.

Empiece con IronBarcode ahora.
green arrow pointer

Preguntas Frecuentes

¿Cómo puedo instalar una biblioteca de lectura de códigos de barras en un proyecto .NET?

Puede instalar la biblioteca IronBarcode a través del Administrador de Paquetes NuGet usando el comando dotnet add package BarCode o través de la interfaz de NuGet de Visual Studio. Alternativamente, descargue el DLL para la instalación manual.

¿Cuál es el método para leer un código de barras desde una imagen usando C#?

Utilice el método BarcodeReader.Read de IronBarcode con una sola línea de código: var results = BarcodeReader.Read('image.png'); Este método detecta y lee todos los formatos de códigos de barras presentes en la imagen.

¿Es posible detectar múltiples códigos de barras en una sola imagen o documento?

Sí, IronBarcode puede detectar y leer automáticamente múltiples códigos de barras en una imagen, PDF o TIFF de múltiples fotogramas, devolviendo el valor, el tipo y la posición de cada código de barras en una colección BarcodeResults.

¿Cómo leo códigos de barras de un PDF usando C#?

Utilice el método BarcodeReader.ReadPdf de IronBarcode para escanear todas las páginas de un documento PDF: var results = BarcodeReader.ReadPdf('document.pdf'); Cada resultado incluye el número de página donde se encontró el código de barras.

¿Qué debo hacer si las imágenes de los códigos de barras están borrosas o rotadas?

Configure BarcodeReaderOptions para manejar imágenes desafiantes estableciendo AutoRotate = true y aplicando filtros de imagen como SharpenFilter o AdaptiveThresholdFilter. Utilice Speed = ExtremeDetail para mayor precisión.

¿Qué formatos de códigos de barras son compatibles en aplicaciones .NET?

IronBarcode es compatible con todos los formatos principales de códigos de barras, como QR Code, Code 128, Code 39, EAN-13, UPC-A, Data Matrix, PDF417 y más. Utilice BarcodeEncoding.All para escanear cualquier formato compatible.

¿Cómo puedo mejorar el rendimiento de escaneo de códigos de barras en una aplicación C#?

Mejore el rendimiento especificando tipos de códigos de barras esperados con ExpectBarcodeTypes, habilitando el procesamiento Multithreaded y eligiendo configuraciones de Speed adecuadas. Para tareas por lotes, utilice BarcodeReader.Read con rutas de archivo.

¿Cuál es el enfoque recomendado para manejar errores de lectura de códigos de barras?

Encapsule la lectura de códigos de barras en bloques try-catch y verifique si los resultados son nulos o vacíos. IronBarcode proporciona mensajes de error detallados y una propiedad Confidence para indicar la fiabilidad de la detección.

¿Puedo extraer imágenes de códigos de barras después de que se escanean?

Sí, el BarcodeResult de IronBarcode incluye una propiedad BarcodeImage que contiene un Bitmap del código de barras detectado, que puede ser guardado o procesado por separado.

¿Cómo leo códigos de barras de páginas específicas dentro de un documento PDF?

Establezca la propiedad PageNumbers en BarcodeReaderOptions para especificar páginas: options.PageNumbers = new[] {1, 2, 3}; Esto optimiza el rendimiento al escanear solo las páginas designadas.

¿Qué formatos de imagen son compatibles con el escaneo de códigos de barras en .NET?

IronBarcode admite el escaneo en formatos como PNG, JPEG, BMP, GIF, TIFF (incluidos los de varios fotogramas) y PDF. Puede cargar imágenes desde rutas de archivo, flujos o arreglos de bytes.

¿Cómo puedo acceder a los datos binarios de los códigos de barras escaneados en C#?

Utilice la propiedad BinaryValue de BarcodeResult para obtener los datos binarios en bruto, especialmente útil para códigos de barras que contienen datos no textuales como información comprimida o protocolos binarios.

Jacob Mellor, Director de Tecnología @ Team Iron
Director de Tecnología

Jacob Mellor es Director de Tecnología en Iron Software y un ingeniero visionario que lidera la tecnología PDF en C#. Como el desarrollador original detrás de la base de código central de Iron Software, ha moldeado la arquitectura de productos de la compañía desde ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado