Cómo usar imágenes de entrada para procesamiento de OCR en C#

How to Read from Streams

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

Stream data refers to a continuous flow of binary information that can be read from or written to. In the context of programming and data handling, streams are used to efficiently process data that may be too large to fit entirely in memory. Streams allow data to be read or written in smaller, manageable chunks.

IronOCR's import methods also accept data streams of images to be imported and read. This can be done by simply passing the stream data into one of the import methods. The method will handle all the necessary steps to import the image.

Quickstart: Use a Stream for OCR Input in Seconds

This simple example shows how to start OCR immediately by feeding a System.IO.Stream into IronOCR, letting you skip file paths and jump straight to recognized text with minimal setup and code.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronOCR with NuGet Package Manager

    PM > Install-Package IronOcr

  2. Copy and run this code snippet.

    using var input = new IronOcr.OcrInput(stream);
    var result = new IronOcr.IronTesseract().Read(input);
  3. Deploy to test on your live environment

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


Read Streams Example

First, instantiate the IronTesseract class to perform OCR. Use the FromFile method of AnyBitmap to import the image file. This AnyBitmap object will be able to convert the image data into a stream. Next, use the using statement to create the OcrImageInput object by passing the image stream with the GetStream method of the AnyBitmap object. Finally, use the Read method to perform OCR.

:path=/static-assets/ocr/content-code-examples/how-to/input-streams-read-streams.cs
using IronOcr;
using IronSoftware.Drawing;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Read image file to AnyBitmap
AnyBitmap anyBitmap = AnyBitmap.FromFile("Potter.tiff");

// Import image stream
using var imageInput = new OcrImageInput(anyBitmap.GetStream());
// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);
Imports IronOcr
Imports IronSoftware.Drawing

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Read image file to AnyBitmap
Private anyBitmap As AnyBitmap = AnyBitmap.FromFile("Potter.tiff")

' Import image stream
Private imageInput = New OcrImageInput(anyBitmap.GetStream())
' Perform OCR
Private ocrResult As OcrResult = ocrTesseract.Read(imageInput)
$vbLabelText   $csharpLabel

Specify Scan Region

To improve performance on large images and obtain specific readings from certain regions, you can utilize the CropRectangle class. The OcrImageInput constructor accepts a CropRectangle object as a second parameter. This allows you to specify which region of the image document should be read. In the code example below, I specify that only the chapter number and title region should be read.

:path=/static-assets/ocr/content-code-examples/how-to/input-streams-read-specific-region.cs
using IronOcr;
using IronSoftware.Drawing;
using System;

// Instantiate IronTesseract
IronTesseract ocrTesseract = new IronTesseract();

// Read image file to AnyBitmap
AnyBitmap anyBitmap = AnyBitmap.FromFile("Potter.tiff");

// Specify crop region
Rectangle scanRegion = new Rectangle(800, 200, 900, 400);

// Add image
using var imageInput = new OcrImageInput(anyBitmap.GetStream(), ContentArea: scanRegion);
// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);

// Output the result to console
Console.WriteLine(ocrResult.Text);
Imports IronOcr
Imports IronSoftware.Drawing
Imports System

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Read image file to AnyBitmap
Private anyBitmap As AnyBitmap = AnyBitmap.FromFile("Potter.tiff")

' Specify crop region
Private scanRegion As New Rectangle(800, 200, 900, 400)

' Add image
Private imageInput = New OcrImageInput(anyBitmap.GetStream(), ContentArea:= scanRegion)
' Perform OCR
Private ocrResult As OcrResult = ocrTesseract.Read(imageInput)

' Output the result to console
Console.WriteLine(ocrResult.Text)
$vbLabelText   $csharpLabel

OCR Result

Read specific region

Preguntas Frecuentes

¿Cómo puedo leer streams de imágenes para procesar OCR en .NET C#?

En .NET C#, puedes utilizar los métodos de importación de IronOCR para leer streams de imágenes pasando los datos del stream al constructor OcrImageInput. Este método maneja eficientemente los datos de imagen para el procesamiento OCR.

¿Cuál es el beneficio de usar streams para OCR en IronOCR?

Usar streams permite a IronOCR procesar archivos grandes de imágenes eficientemente al manejar datos en trozos más pequeños y manejables. Este enfoque optimiza el uso de memoria y acelera el proceso OCR.

¿Cómo especifíco una región de una imagen para leerla con OCR en C#?

Para especificar una región de una imagen para OCR usando IronOCR, puedes usar la clase CropRectangle. Pasa esto como un parámetro al constructor OcrImageInput para centrarse en un área específica de la imagen.

¿Puede IronOCR manejar OCR de streams de imágenes en tiempo real?

Sí, IronOCR puede manejar OCR de streams de imágenes en tiempo real procesando continuamente los datos de imagen a medida que se reciben. Esta característica es beneficiosa para aplicaciones que requieren reconocimiento de texto inmediato.

¿Cómo puedo mejorar el rendimiento de OCR en imágenes grandes?

Para mejorar el rendimiento de OCR en imágenes grandes usando IronOCR, especifica una región de escaneo con la clase CropRectangle para limitar el procesamiento a áreas relevantes, reduciendo la cantidad de datos que necesita ser analizado.

¿Cuál es el papel del constructor OcrImageInput en IronOCR?

El constructor OcrImageInput en IronOCR se utiliza para importar streams de imágenes y definir opcionalmente una región específica de interés para el procesamiento OCR. Este simplifica el proceso de preparar imágenes para la extracción de texto.

¿Cómo funciona el método Read en IronOCR?

El método Read en IronOCR ejecuta el proceso de reconocimiento óptico de caracteres en el stream de imagen proporcionado. Extrae texto de los datos de imagen y devuelve los caracteres reconocidos.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 5,044,537 | Versión: 2025.11 recién lanzado