Archivos TIFF mayores de 2 GB no se cargan en IronOCR
Un archivo TIFF mayor a aproximadamente 2 GB no se carga, y la imagen nunca llega a OCR.
Loaded pages: 0
2026.8.1. Actualice a esa versión o posterior para la corrección. Los pasos a continuación son para usuarios que aún usan una versión anterior.IronOCR carga la entrada de imagen en un único búfer en memoria a través de su tipo interno AnyBitmap. Ese búfer está indexado por un entero de 32 bits, por lo que se limita a aproximadamente 2 GB sin importar cuánto memoria del sistema esté disponible. Un TIFF ligeramente por encima de ese límite no puede mantenerse, por lo que la carga falla.
OcrInput.LoadImage(filePath) crea un AnyBitmap internamente y materializa toda la imagen en un búfer. En versiones anteriores a la corrección, esta llamada devuelve cero páginas cargadas en lugar de lanzar una excepción clara. Esa falla silenciosa es un problema conocido y se planea una excepción más clara. El diseño de un solo búfer es un límite arquitectónico; la transmisión nativa de TIFF por página, que evitaría almacenar en búfer todo el archivo, no estaba disponible antes de 2026.8.1.
Entorno
- Idioma/Ejecución: .NET (multiplataforma, el límite es una restricción de ejecución, no específica del sistema operativo)
Metadatos de la versión
- Versión encontrada:
2026.5.2 - Versión resuelta:
2026.8.1
Solución
Recomendado: actualice a IronOCR 2026.8.1 o posterior, donde esta limitación se resuelve.
Si aún no puede actualizar, divida el TIFF en trozos de menos de 2 GB y cargue cada trozo con OcrInput.LoadImage(byte[]), no la ruta del archivo, para que nada mayor que el límite llegue a AnyBitmap. A continuación, se presentan dos enfoques.
Opción A: Magick.NET (configuración más sencilla)
Agregue Magick.NET para poder dividir el TIFF antes de entregarlo a IronOCR. Elija la variante que coincida con su proyecto (Q8/Q16, AnyCPU/x64).
dotnet add package Magick.NET-Q16-AnyCPU
Abra el TIFF como un MagickImageCollection, divídalo en trozos con el número de páginas que cada uno se mantenga por debajo de 2 GB, convierta cada trozo en un arreglo de bytes, y cárguelo con OcrInput.LoadImage(byte[]).
var inputPath = "input.tiff";
var pagesPerChunk = 100;
using var allPages = new MagickImageCollection(inputPath);
int chunkNumber = 1;
for (int i = 0; i < allPages.Count; i += pagesPerChunk)
{
using var chunk = new MagickImageCollection();
for (int j = i; j < Math.Min(i + pagesPerChunk, allPages.Count); j++)
{
chunk.Add(allPages[j].Clone());
}
foreach (var image in chunk)
{
image.SetCompression(CompressionMethod.LZW);
}
var chunkBytes = chunk.ToByteArray();
using (var ocrInput = new OcrInput())
{
ocrInput.LoadImage(chunkBytes);
var pages = ocrInput.GetPages().ToList();
Console.WriteLine($"Loaded pages: {pages.Count}");
var result = new IronTesseract().Read(ocrInput);
Console.WriteLine("OCR Text Length: " + (result.Text?.Length ?? 0));
}
Console.WriteLine($"Chunk {chunkNumber} processed");
chunkNumber++;
}
Ajuste pagesPerChunk para sus datos. Bájelo si una porción se aproxima a 2 GB o si la memoria es ajustada; súbalo para páginas más pequeñas para reducir la sobrecarga.
Tenga en cuenta Magick.NET en su implementación. Incluye binarios nativos de ImageMagick, lo que añade al tamaño del paquete y trae una dependencia nativa.
Opción B: LibTiff.NET (completamente gestionado, sin dependencia nativa)
Una alternativa completamente gestionada que copia las páginas a nivel de datos sin decodificar o re-codificar. Útil cuando importa la huella de dependencia nativa o la fidelidad exacta de píxeles/compresión.
Requisitos previos:
- IronOCR (
IronTesseract) en un proyecto .NET. BitMiracle.LibTiff.NET(comando de instalación abajo).- Los tipos de LibTiff utilizados aquí residen en el espacio de nombres
BitMiracle.LibTiff.Classic.
1. Agregue el paquete LibTiff.NET:
dotnet add package BitMiracle.LibTiff.NET
2. Agregue el asistente TiffPageSplitter: Copia cada página a nivel de tira o mosaico crudo, por lo que los datos de píxeles y la compresión se preservan exactamente sin decodificar o re-codificar. Transmite páginas una por una, por lo que la memoria máxima es aproximadamente un trozo en lugar de todo el archivo, y produce trozos de varias páginas que cada uno se mantenga por debajo del límite de tamaño.
/// <summary>
/// Splits a multi-page TIFF into single-page TIFF byte streams without ever
/// holding the whole file in memory. Each page is copied at the raw
/// (still-encoded) strip/tile level, so pixel data and compression are
/// preserved exactly - there is no decode/re-encode step.
///
/// This is the chunking step only. It produces sub-2 GB single-page byte
/// arrays; feeding them to IronOCR (which is where the AnyBitmap 2 GB
/// single-buffer limit lives) is the consumer's job - see TiffOcrExample.
/// </summary>
public static class TiffPageSplitter
{
// Tags that describe how a page's raw strip/tile data is encoded.
// With a raw copy nothing is re-encoded, so every one of these must be
// carried over verbatim or the copied bytes become uninterpretable.
// Extend this list if your TIFFs carry tags not covered here
// (e.g. ICC profiles, EXTRASAMPLES for alpha channels).
private static readonly TiffTag[] ScalarIntTags =
{
TiffTag.IMAGEWIDTH,
TiffTag.IMAGELENGTH,
TiffTag.BITSPERSAMPLE,
TiffTag.SAMPLESPERPIXEL,
TiffTag.COMPRESSION,
TiffTag.PHOTOMETRIC,
TiffTag.FILLORDER,
TiffTag.PLANARCONFIG,
TiffTag.ORIENTATION,
TiffTag.RESOLUTIONUNIT,
TiffTag.PREDICTOR, // required for LZW / Deflate raw copies
TiffTag.SAMPLEFORMAT,
TiffTag.T4OPTIONS, // CCITT Group 3
TiffTag.T6OPTIONS, // CCITT Group 4
TiffTag.SUBFILETYPE,
};
private static readonly TiffTag[] ScalarDoubleTags =
{
TiffTag.XRESOLUTION, // DPI directly affects OCR accuracy
TiffTag.YRESOLUTION,
};
/// <summary>
/// Lazily yields each page of <paramref name="inputPath"/> as a standalone
/// single-page TIFF. The source file stays open for the lifetime of the
/// enumeration and only one page is materialised at a time, so peak memory
/// is roughly one page rather than the whole file.
/// </summary>
public static IEnumerable<byte[]> SplitTiffToPages(string inputPath)
{
using (Tiff input = Tiff.Open(inputPath, "r"))
{
if (input == null)
throw new InvalidOperationException($"Could not open TIFF: {inputPath}");
int pageCount = input.NumberOfDirectories();
for (int page = 0; page < pageCount; page++)
{
input.SetDirectory((short)page);
yield return ExtractCurrentPage(input);
}
}
}
private static byte[] ExtractCurrentPage(Tiff input)
{
using (var ms = new MemoryStream())
{
// Default TiffStream operates on the MemoryStream passed as clientData.
using (Tiff output = Tiff.ClientOpen("InMemory", "w", ms, new TiffStream()))
{
if (output == null)
throw new InvalidOperationException("Could not create in-memory TIFF.");
CopyTags(input, output);
if (input.IsTiled())
CopyRawTiles(input, output);
else
CopyRawStrips(input, output);
output.WriteDirectory();
}
return ms.ToArray();
}
} private static void CopyTags(Tiff input, Tiff output)
{ foreach (TiffTag tag in ScalarIntTags)
{
FieldValue[] v = input.GetField(tag);
if (v != null && v.Length > 0)
output.SetField(tag, v[0].ToInt());
}
foreach (TiffTag tag in ScalarDoubleTags)
{
FieldValue[] v = input.GetField(tag);
if (v != null && v.Length > 0)
output.SetField(tag, v[0].ToDouble());
}
// Strip vs tile layout must match the raw data exactly, otherwise the
// raw bytes won't line up with the declared boundaries.
if (input.IsTiled())
{
output.SetField(TiffTag.TILEWIDTH, input.GetField(TiffTag.TILEWIDTH)[0].ToInt());
output.SetField(TiffTag.TILELENGTH, input.GetField(TiffTag.TILELENGTH)[0].ToInt());
}
else
{
FieldValue[] rps = input.GetField(TiffTag.ROWSPERSTRIP);
if (rps != null && rps.Length > 0)
output.SetField(TiffTag.ROWSPERSTRIP, rps[0].ToInt());
}
// Palette images: the colour map is required to interpret pixel indices.
FieldValue[] cmap = input.GetField(TiffTag.COLORMAP);
if (cmap != null && cmap.Length >= 3)
output.SetField(TiffTag.COLORMAP,
cmap[0].ToShortArray(), cmap[1].ToShortArray(), cmap[2].ToShortArray());
}
private static void CopyRawStrips(Tiff input, Tiff output)
{
int stripCount = input.NumberOfStrips();
int[] byteCounts = input.GetField(TiffTag.STRIPBYTECOUNTS)[0].ToIntArray();
for (int strip = 0; strip < stripCount; strip++)
{
byte[] buffer = new byte[byteCounts[strip]];
int read = input.ReadRawStrip(strip, buffer, 0, buffer.Length);
output.WriteRawStrip(strip, buffer, read);
}
}
private static void CopyRawTiles(Tiff input, Tiff output)
{
int tileCount = input.NumberOfTiles();
int[] byteCounts = input.GetField(TiffTag.TILEBYTECOUNTS)[0].ToIntArray();
for (int tile = 0; tile < tileCount; tile++)
{
byte[] buffer = new byte[byteCounts[tile]];
int read = input.ReadRawTile(tile, buffer, 0, buffer.Length);
output.WriteRawTile(tile, buffer, read);
}
}
/// <summary>
/// Lazily yields multi-page TIFF chunks (the equivalent of the old
/// Magick.NET 100-pages-per-chunk approach). A new chunk is started when
/// adding the next page would push the chunk past
/// <paramref name="maxChunkBytes"/>, or when <paramref name="maxPagesPerChunk"/>
/// is reached - whichever comes first.
///
/// Size is the real guard: page count alone can exceed the 2 GB AnyBitmap
/// limit on large pages. The byte total here is the encoded (compressed)
/// size, which is a cheap proxy - validate the cap against your actual
/// pages, since decoded size can be much larger than encoded.
/// </summary>
public static IEnumerable<byte[]> SplitTiffToChunks(
string inputPath,
int maxPagesPerChunk = 100,
long maxChunkBytes = 1_500_000_000L)
{
using (Tiff input = Tiff.Open(inputPath, "r"))
{
if (input == null)
throw new InvalidOperationException($"Could not open TIFF: {inputPath}");
int pageCount = input.NumberOfDirectories();
int page = 0;
while (page < pageCount)
{
using (var ms = new MemoryStream())
{
using (Tiff output = Tiff.ClientOpen("InMemory", "w", ms, new TiffStream()))
{
if (output == null)
throw new InvalidOperationException("Could not create in-memory TIFF.");
int pagesInChunk = 0;
long chunkBytes = 0;
while (page < pageCount && pagesInChunk < maxPagesPerChunk)
{
input.SetDirectory((short)page);
long pageBytes = RawPageByteSize(input);
// Stop before exceeding the cap, but always allow at
// least one page so a single large page still goes through.
if (pagesInChunk > 0 && chunkBytes + pageBytes > maxChunkBytes)
break;
CopyTags(input, output);
if (input.IsTiled())
CopyRawTiles(input, output);
else
CopyRawStrips(input, output);
output.WriteDirectory();
// finalise this page as one directory in the chunk
chunkBytes += pageBytes;
pagesInChunk++;
page++;
}
}
yield return ms.ToArray();
}
}
}
}
private static long RawPageByteSize(Tiff page)
{
TiffTag tag = page.IsTiled() ? TiffTag.TILEBYTECOUNTS : TiffTag.STRIPBYTECOUNTS;
int[] counts = page.GetField(tag)[0].ToIntArray();
long total = 0;
foreach (int c in counts)
total += c;
return total;
}
}
El asistente copia cada página a nivel de tira o mosaico crudo, por lo que los datos de píxeles y compresión se trasladan exactamente. La memoria máxima se mantiene en torno a un trozo porque las páginas se transmiten una a la vez.
3. Reconozca cada trozo: Itere SplitTiffToChunks y cargue cada arreglo de bytes con OcrInput.LoadImage(byte[]), no la ruta del archivo, de modo que nada mayor que el límite llegue jamás a AnyBitmap.
var inputPath = "2gb_benchmark1200.tiff";
var ocr = new IronTesseract();
int chunk = 0;
foreach (byte[] chunkBytes in TiffPageSplitter.SplitTiffToChunks(inputPath, maxPagesPerChunk: 100))
{
using (var ocrInput = new OcrInput())
{
ocrInput.LoadImage(chunkBytes);
// loads every page in the chunk
var result = ocr.Read(ocrInput);
Console.WriteLine($"Chunk {chunk}: {result.Text?.Length ?? 0} chars");
}
chunk++;
}
Ajuste maxPagesPerChunk y maxChunkBytes para sus datos. Redúzcalos si una sección se aproxima a 2 GB una vez decodificada o si la memoria está limitada; Aumente el conteo de páginas para páginas más pequeñas para reducir el overhead.
Eligiendo entre las dos
- Opción A (Magick.NET): más rápida de configurar y no necesita código de asistente personalizado, pero incluye binarios nativos de ImageMagick (aumentando el tamaño del paquete y la huella de implementación) y decodifica y luego re-codifica cada página.
- Opción B (LibTiff.NET): completamente gestionada sin dependencia nativa, copia páginas a nivel de tira/mosaico crudo sin paso de decodificación o re-codificación (preservando exactamente la compresión original y los datos de píxeles), y transmite una página a la vez para menor memoria máximo. Requiere más código de configuración y solo lleva los tags TIFF que el asistente lista explícitamente.
Notas y limitaciones
- El límite de 2 GB es un límite arquitectónico del
AnyBitmapde IronOCR (un único búfer indexado por un entero de 32 bits), no un problema del sistema operativo o la memoria disponible. La transmisión nativa por página de TIFF no lo abordó hasta2026.8.1. - En versiones anteriores a la corrección,
OcrInput.LoadImage(filePath)devuelve cero páginas cargadas en lugar de lanzar un error claro cuando el archivo es demasiado grande. Esta falla silenciosa es un problema conocido y se planea una excepción más clara. La división evita esto manteniendo cada entrada por debajo del límite. - El divisor de LibTiff.NET solo lleva los tags TIFF listados en
ScalarIntTagsyScalarDoubleTags. Si sus TIFF utilizan tags no cubiertos allí, por ejemplo perfiles ICC oEXTRASAMPLESpara canales alfa, extienda esas listas o los bytes copiados en crudo pueden ser malinterpretados. maxChunkBytesse mide contra el tamaño codificado (comprimido), que es solo un proxy barato. El tamaño decodificado puede ser mucho mayor, así que valide el límite contra sus páginas reales. El valor predeterminado es 1.5 GB para dejar margen antes del límite de 2 GB.
Referencias
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 estructurados y visualmente atractivos.