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

How to Read Images

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

OCR, or Optical Character Recognition, is a technology that is used to recognize and extract text from images. This technology is particularly useful for digitizing printed documents, as it allows you to extract and work with the textual content from scanned pages, photographs, or other image files.

IronOCR supports various image formats, including jpg, png, gif, tiff, and bmp. Image filters are also available to enhance the reading capability.

Quickstart: Read an Image File with IronOCR

Use IronOCR in just one line to extract text from an image. This example shows how with a few easy steps you can load an image and read its text using the Read method on IronTesseract for fast OCR setup.

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.

    var result = new IronTesseract().Read(new OcrImageInput("Potter.png"));
  3. Deploy to test on your live environment

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


Read Images Example

Begin by instantiating the IronTesseract class to enable OCR. Utilize the 'using' statement to create an OcrImageInput object, specifying the image file path. This ensures the proper disposal of resources when they are no longer needed. IronOCR supports input images in various formats, including jpg, png, gif, tiff, and bmp. Finally, use the Read method to perform OCR.

Por favor nota Starting from version 2025.6:

  • Loading TIFF images now consistently delivers faster performance.
  • Reading TIFF images show performance improvements that depend on the machine's GPU. Some users may experience up to twice the speed, while others may see performance similar to previous versions
:path=/static-assets/ocr/content-code-examples/how-to/input-images-read.cs
using IronOcr;

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

// Add image
using var imageInput = new OcrImageInput("Potter.png");

// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);
Imports IronOcr

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Add image
Private imageInput = New OcrImageInput("Potter.png")

' Perform OCR
Private ocrResult As OcrResult = ocrTesseract.Read(imageInput)
$vbLabelText   $csharpLabel
Read PNG image

Visit the How to Read Multi-Frame/Page GIFs and TIFFs article to learn more about reading TIFF and GIF images.

Import Images as Bytes

Apart from the plain old filepath, the OcrImageInput class also accepts image information in the form of bytes, AnyBitmap, Stream, as well as Image. The AnyBitmap is a bitmap object of IronSoftware.Drawing.AnyBitmap.

:path=/static-assets/ocr/content-code-examples/how-to/input-images-import-byte.cs
using IronOcr;
using System.IO;

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

// Read byte from file
byte[] data = File.ReadAllBytes("Potter.tiff");

// Import image byte
using var imageInput = new OcrImageInput(data);
// Perform OCR
OcrResult ocrResult = ocrTesseract.Read(imageInput);
Imports IronOcr
Imports System.IO

' Instantiate IronTesseract
Private ocrTesseract As New IronTesseract()

' Read byte from file
Private data() As Byte = File.ReadAllBytes("Potter.tiff")

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

Specify Scan Region

A CropRectangle is also accepted when instantiating the OcrImageInput class. This allows you to specify which region of the image document should be OCR'ed. Depending on the image document, specifying the region to scan can significantly improve performance. In the code example below, you specify that only the chapter number and title should be read.

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

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

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

// Add image
using var imageInput = new OcrImageInput("Potter.tiff", 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()

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

' Add image
Private imageInput = New OcrImageInput("Potter.tiff", 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 realizar OCR en una imagen en .NET C#?

Puede realizar OCR en una imagen en .NET C# utilizando la biblioteca IronOCR. Comience descargando IronOCR desde NuGet, instancie la clase IronTesseract, y utilice la clase OcrImageInput para ingresar una imagen. Luego, aplique el método Read para extraer texto de la imagen.

¿Qué formatos de imagen se pueden procesar usando OCR en .NET?

IronOCR soporta varios formatos de imagen para el procesamiento de OCR, incluyendo jpg, png, gif, tiff y bmp. Esto permite una integración flexible con diferentes tipos de archivos de imagen.

¿Cómo puedo especificar un área específica de una imagen para OCR en C#?

En IronOCR, puedes definir un área específica de una imagen para ser procesada utilizando un CropRectangle al instanciar la clase OcrImageInput. Esto puede mejorar el rendimiento enfocando la operación OCR en una región particular.

¿Es posible leer imágenes desde un arreglo de bytes para OCR en C#?

Sí, IronOCR le permite ingresar imágenes como arreglos de bytes, AnyBitmap, Stream o Image. Esta flexibilidad le permite realizar OCR en datos de imagen disponibles en diferentes formatos.

¿Cómo puedo asegurar una gestión eficiente de memoria durante las operaciones de OCR en C#?

Para gestionar la memoria eficientemente durante las operaciones de OCR con IronOCR, use la declaración 'using' al crear un objeto OcrImageInput. Esto asegura que los recursos se liberen adecuadamente cuando ya no se necesiten.

¿Puedo procesar imágenes de múltiples cuadros o páginas para OCR en C#?

Sí, IronOCR admite la lectura de imágenes de múltiples cuadros o páginas, como GIFs y TIFFs. Esta capacidad le permite realizar OCR en archivos de imagen complejos que contienen múltiples cuadros o páginas.

¿Cómo puedo mejorar el reconocimiento de texto en OCR usando filtros de imagen?

IronOCR proporciona filtros de imagen que se pueden usar para mejorar las capacidades de reconocimiento de texto. Al aplicar estos filtros, puede mejorar la precisión y confiabilidad del proceso de OCR en varios formatos de imagen.

¿Cuáles son los beneficios de usar IronOCR para la lectura de imágenes en C#?

IronOCR ofrece varios beneficios para la lectura de imágenes en C#, incluyendo soporte para múltiples formatos de imagen, la capacidad de especificar regiones de escaneo, y la capacidad de ingresar imágenes como bytes o streams. Estas características permiten un procesamiento OCR eficiente y flexible en aplicaciones .NET.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
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