Arquivos TIFF maiores que 2 GB falham ao carregar no IronOCR
Um arquivo TIFF maior que aproximadamente 2 GB falha ao carregar, e a imagem nunca atinge o OCR.
Loaded pages: 0
2026.8.1. Atualize para essa versão ou posterior para a correção. Os passos abaixo são para usuários que ainda estão em uma versão anterior.IronOCR carrega a entrada de imagem em um único buffer em memória através de seu tipo interno AnyBitmap. Esse buffer é indexado por um inteiro de 32 bits, então é limitado a aproximadamente 2 GB, independentemente de quanta memória do sistema está disponível. Um TIFF ligeiramente acima desse limite não pode ser mantido, por isso o carregamento falha.
OcrInput.LoadImage(filePath) cria um AnyBitmap internamente e materializa a imagem inteira em um único buffer. Em versões anteriores à correção, essa chamada retorna zero páginas carregadas em vez de lançar uma exceção clara. Essa falha silenciosa é um problema conhecido e uma exceção mais clara está planejada. O design de um único buffer é um limite arquitetural; streaming TIFF nativo por página, que evitaria o buffering do arquivo inteiro, não estava disponível antes de 2026.8.1.
Ambiente
- Linguagem/Runtime: .NET (multiplataforma, o limite é uma restrição de runtime, não específica do sistema operacional)
Metadados da Versão
- Versão Encontrada:
2026.5.2 - Versão Resolvida:
2026.8.1
Solução
Recomenda-se: atualizar para IronOCR 2026.8.1 ou superior, onde esta limitação é resolvida.
Se você não puder atualizar ainda, divida o TIFF em partes menores que 2 GB e carregue cada parte com OcrInput.LoadImage(byte[]), não o caminho do arquivo, assim nada maior que o limite chega a AnyBitmap. Seguem duas abordagens.
Opção A: Magick.NET (configuração mais simples)
Adicione Magick.NET para que você possa dividir o TIFF antes de entregá-lo ao IronOCR. Escolha a variante que corresponde ao seu projeto (Q8/Q16, AnyCPU/x64).
dotnet add package Magick.NET-Q16-AnyCPU
Abra o TIFF como um MagickImageCollection, divida em partes de contagem de páginas que cada uma fique abaixo de 2 GB, converta cada parte para um array de bytes e carregue com 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 seus dados. Reduza-o se um pedaço se aproximar de 2 GB ou se a memória estiver apertada; aumente-o para páginas menores para reduzir a sobrecarga.
Leve em conta Magick.NET em seu deployment. Ele envia binários nativos ImageMagick, que adicionam ao tamanho do pacote e trazem um impacto de dependência nativa.
Opção B: LibTiff.NET (totalmente gerenciado, sem dependência nativa)
Uma alternativa totalmente gerenciada que copia páginas no nível bruto, sem passo de decodificação ou recodificação. Útil quando um impacto de dependência nativa ou fidelidade exata de pixels/compactação é importante.
Pré-requisitos:
- IronOCR (
IronTesseract) em um projeto .NET. BitMiracle.LibTiff.NET(comando de instalação abaixo).- Os tipos LibTiff usados aqui vivem no namespace
BitMiracle.LibTiff.Classic.
1. Adicione o pacote LibTiff.NET:
dotnet add package BitMiracle.LibTiff.NET
2. Adicione o helper TiffPageSplitter: Ele copia cada página no nível de tira ou tile bruta, de modo que dados de pixel e compactação são preservados exatamente sem decodificar ou recodificar. Ele transmite páginas uma de cada vez, então a memória máxima é aproximadamente uma parte em vez do arquivo inteiro e gera partes de múltiplas páginas que cada uma fica abaixo do limite de tamanho.
/// <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;
}
}
O helper copia cada página no nível de tira ou tile bruto, de modo que os dados de pixel e compressão são transferidos exatamente. A memória máxima permanece em torno de uma parte porque as páginas são transmitidas uma de cada vez.
3. OCR cada parte: Itere SplitTiffToChunks e carregue cada array de bytes com OcrInput.LoadImage(byte[]), não o caminho do arquivo, assim nada maior que o limite atinge 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 e maxChunkBytes para seus dados. Reduza-os se uma parte se aproximar de 2 GB quando decodificada ou se a memória estiver apertada; aumente a contagem de páginas para páginas menores a fim de reduzir a sobrecarga.
Escolhendo entre os dois
- Opção A (Magick.NET): mais rápido para configurar e não precisa de código de assistente personalizado, mas envia binários nativos do ImageMagick (aumentando o tamanho do pacote e a pegada de deployment) e decodifica e depois recodifica cada página.
- Opção B (LibTiff.NET): totalmente gerenciado sem dependência nativa, copia páginas no nível de tira/tile bruto sem passo de decodificação ou recodificação (preservando exatamente a compressão original e dados de pixel), e transmite uma página de cada vez para menor memória máxima. Requer mais código de configuração e só transfere as tags TIFF que o helper lista explicitamente.
Notas e Limitações
- O limite de 2 GB é uma limitação arquitetural do
AnyBitmapdo IronOCR (um único buffer indexado por um inteiro de 32 bits), não um problema do sistema operacional ou da memória disponível. Streaming TIFF nativo por página não o resolveu até2026.8.1. - Em versões anteriores à correção,
OcrInput.LoadImage(filePath)retorna zero páginas carregadas em vez de lançar um erro claro quando o arquivo é muito grande. Essa falha silenciosa é um problema conhecido e uma exceção mais clara está planejada. Fragmentação contorna isso mantendo cada entrada abaixo do limite. - O separador LibTiff.NET só transfere as tags TIFF listadas em
ScalarIntTagseScalarDoubleTags. Se seus TIFFs usarem tags não cobertas lá, por exemplo perfis ICC ouEXTRASAMPLESpara canais alfa, amplie essas listas ou os bytes copiados brutos podem ser mal interpretados. maxChunkBytesé medido contra o tamanho codificado (compactado), que é apenas uma aproximação barata. O tamanho decodificado pode ser muito maior, então valide o limite em relação às suas páginas reais. O padrão é 1,5 GB para deixar folga sob o limite de 2 GB.
Referências
Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.