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

How to read Barcodes from Streams

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

MemoryStream is a class in the .NET Framework that provides a way to read from and write to a stream that is stored in memory. It is a type of stream that can be used to manipulate data that is not stored in a physical file, but rather in memory.

Apart from reading barcodes from image files or PDF files, IronBarcode also excels in reading barcodes from streams. Being a great API in an application, IronBarcode is able to accept PDF document or image stream as an input and output the read result of the barcodes inside the stream. Now let us see how we can achieve this.

Quickstart: Read Barcode Directly from Image Stream

Use just two lines of code with IronBarcode to read barcodes from any image stream—no need to write to disk first. This quick example shows how simple it is to get started with stream-based barcode reading in .NET.

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 result = IronBarCode.BarcodeReader.Read(myImageStream);
    Console.WriteLine(result[0].Text);
  3. Deploy to test on your live environment

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

Read barcodes from Image stream

In this section, we will show you how to use IronBarcode to read an image stream, as well as multiple image streams stored in a List<MemoryStream>. Below is the corrected block of code with comments to help you understand the process:

using IronBarCode;
using System;
using System.Collections.Generic;
using System.IO;

class BarcodeFromImageStream
{
    static void Main(string[] args)
    {
        // Create a list of MemoryStreams to store image streams
        List<MemoryStream> imageStreams = new List<MemoryStream>
        {
            // Example of adding an existing MemoryStream object to the list
            new MemoryStream(File.ReadAllBytes("example1.png")),
            new MemoryStream(File.ReadAllBytes("example2.png"))
        };

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

class BarcodeFromImageStream
{
    static void Main(string[] args)
    {
        // Create a list of MemoryStreams to store image streams
        List<MemoryStream> imageStreams = new List<MemoryStream>
        {
            // Example of adding an existing MemoryStream object to the list
            new MemoryStream(File.ReadAllBytes("example1.png")),
            new MemoryStream(File.ReadAllBytes("example2.png"))
        };

using IronBarCode;
using IronSoftware.Drawing;
using System;
using System.Collections.Generic;
using System.IO;

List<MemoryStream> list = new List<MemoryStream>();
list.Add(AnyBitmap.FromFile("image1.jpg").ToStream());
list.Add(AnyBitmap.FromFile("image2.jpg").ToStream());
list.Add(AnyBitmap.FromFile("image3.png").ToStream());

var myBarcode = BarcodeReader.Read(list);

foreach (var barcode in myBarcode)
{
    Console.WriteLine(barcode.ToString());
}
Imports IronBarCode
Imports System
Imports System.Collections.Generic
Imports System.IO

Friend Class BarcodeFromImageStream
	Shared Sub Main(ByVal args() As String)
		' Create a list of MemoryStreams to store image streams
		Dim imageStreams As New List(Of MemoryStream) From {
			New MemoryStream(File.ReadAllBytes("example1.png")),
			New MemoryStream(File.ReadAllBytes("example2.png"))
		}

Dim IronBarCode As using
Using IronSoftware.Drawing
	Dim System As using
	Using System.Collections.Generic
		Using System.IO
			
			Dim list As New List(Of MemoryStream)()
			list.Add(AnyBitmap.FromFile("image1.jpg").ToStream())
			list.Add(AnyBitmap.FromFile("image2.jpg").ToStream())
			list.Add(AnyBitmap.FromFile("image3.png").ToStream())
			
			Dim myBarcode = BarcodeReader.Read(list)
			
			For Each barcode In myBarcode
				Console.WriteLine(barcode.ToString())
			Next barcode
		End Using
	End Using
End Using
$vbLabelText   $csharpLabel

From the code snippet above, IronBarcode can accept an object or a list of MemoryStream objects into the BarcodeReader.Read() method and read the stream objects as input. The example shows how to convert an image file into a MemoryStream object and read the barcodes present in the stream directly.

Read barcodes from PDF document stream

In this section, we will show you how to use IronBarcode to read a PDF document file as a MemoryStream object or a MemoryStream list of PDF documents. Here is the improved block of code:

:path=/static-assets/barcode/content-code-examples/how-to/read-barcodes-from-streams-2.cs
using IronBarCode;
using IronPdf;
using System;
using System.IO;

MemoryStream document = PdfDocument.FromFile(@"file_path.pdf").Stream;

var myBarcode = BarcodeReader.ReadPdf(document);

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

Private document As MemoryStream = PdfDocument.FromFile("file_path.pdf").Stream

Private myBarcode = BarcodeReader.ReadPdf(document)

For Each value In myBarcode
	Console.WriteLine(value.ToString())
Next value
$vbLabelText   $csharpLabel

As seen in the code snippet above, reading barcodes from a PDF document as a MemoryStream object is quite similar to reading barcodes from images. The primary difference is the method used: BarcodeReader.ReadPdf() is specifically used for PDF documents. In the example, we use the IronPDF library as a helper to convert a PDF document to a MemoryStream object. If there are multiple PDF documents that you want IronBarcode to read, it is recommended to merge all the PDF documents into one PDF document stream and feed it to the BarcodeReader.ReadPdf() method. Feel free to experiment and make the library work for your specific needs!

Preguntas Frecuentes

¿Cómo leo códigos de barras de un flujo de imágenes en C#?

Puedes leer códigos de barras de un flujo de imágenes en C# usando IronBarcode. Convierte los archivos de imagen en objetos MemoryStream y luego utiliza el método BarcodeReader.Read() para decodificar los códigos de barras de estos flujos.

¿Cómo puedo leer códigos de barras de un flujo de documentos PDF usando .NET?

Para leer códigos de barras de un flujo de documentos PDF en .NET, usa el método BarcodeReader.ReadPdf() de IronBarcode. Primero, convierte tus documentos PDF en objetos MemoryStream, posiblemente usando IronPDF, y luego pásalos al método.

¿Puedo leer varios códigos de barras de un solo flujo de PDF?

Sí, el método BarcodeReader.ReadPdf() de IronBarcode puede procesar un solo flujo de PDF y devolver múltiples objetos BarcodeResult, cada uno representando un código de barras encontrado en el PDF.

¿Cuál es la ventaja de usar MemoryStream para la lectura de códigos de barras en .NET?

Usar MemoryStream permite una manipulación eficiente de datos en memoria, lo que lo hace ideal para escenarios donde deseas leer códigos de barras sin depender del almacenamiento en archivos físicos.

¿Qué debo hacer si tengo múltiples documentos PDF para procesar códigos de barras?

Si tienes múltiples documentos PDF, considera combinarlos en un solo flujo de PDF. Este se puede leer eficientemente usando el método BarcodeReader.ReadPdf() para extraer todos los códigos de barras.

¿Es posible leer códigos de barras tanto de imágenes como de flujos de PDFs en una sola aplicación?

Sí, IronBarcode admite la lectura de códigos de barras tanto de flujos de imágenes como de PDFs. Puedes usar BarcodeReader.Read() para imágenes y BarcodeReader.ReadPdf() para PDFs dentro de la misma aplicación.

¿Cómo puedo convertir un archivo de imagen a un MemoryStream en C#?

Convierte un archivo de imagen a un MemoryStream en C# leyendo los bytes de la imagen usando File.ReadAllBytes() y pasando la matriz de bytes al constructor de MemoryStream.

¿Necesito bibliotecas adicionales para convertir archivos PDF a MemoryStreams?

Aunque IronPDF puede usarse para facilitar la conversión de archivos PDF a objetos MemoryStream, IronBarcode puede manejar directamente flujos de PDF para la lectura de códigos de barras.

¿Cuál es la diferencia entre leer códigos de barras de flujos de imagen y PDF?

La principal diferencia es el método usado: BarcodeReader.Read() es para flujos de imágenes, mientras que BarcodeReader.ReadPdf() está específicamente diseñado para flujos de documentos PDF.

¿Hay ejemplos de código para leer códigos de barras de flujos en C#?

Sí, el artículo proporciona código de ejemplo en C# que demuestra cómo leer códigos de barras tanto de flujos de imagen como de PDF usando IronBarcode, destacando el proceso de conversión a objetos MemoryStream.

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