在IronOCR中加载超过2 GB的TIFF文件失败
大约超过2 GB的TIFF文件无法加载,图像无法到达OCR。
Loaded pages: 0
2026.8.1中已解决。 升级到该版本或更高版本以获取修复。 以下步骤适用于仍在使用早期版本的用户。IronOCR通过其内部AnyBitmap类型将图像输入加载到单个内存缓冲区中。 该缓冲区由32位整数索引,因此无论系统内存有多少,它都限制在大约2 GB。 略高于该限制的TIFF无法被容纳,因此加载失败。
OcrInput.LoadImage(filePath)在内部创建AnyBitmap并将整个图像具体化到一个缓冲区中。 在修复之前的版本中,此调用返回零加载页,而不是抛出明确的异常。 这种静默失败是一个已知问题,计划提供更清晰的异常。 单缓冲设计是一个架构限制; 本机逐页TIFF流,避免缓冲整个文件,在2026.8.1之前不可用。
环境
- 语言/运行时: .NET(跨平台,限制是运行时限制,而不是操作系统特定)
版本元数据
- 发现版本:
2026.5.2 - 解决版本:
2026.8.1
解决方案
推荐: 升级到IronOCR 2026.8.1或更高版本,解决此限制。
如果您还不能升级,请将TIFF拆分为小于2 GB的块,并使用OcrInput.LoadImage(byte[])加载每个块,而不是使用文件路径,因此没有超过限制的内容到达AnyBitmap。 以下是两种方法。
选项A:Magick.NET(最简单的设置)
添加Magick.NET以便在将TIFF交给IronOCR之前拆分它。 选择与您的项目匹配的变体(Q8/Q16,AnyCPU/x64)。
dotnet add package Magick.NET-Q16-AnyCPU
将TIFF作为MagickImageCollection打开,将其拆分为每个小于2 GB的页数块,将每个块转换为字节数组,并使用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++;
}
根据您的数据调整pagesPerChunk。 如果块接近 2 GB 或内存紧张,请降低大小; 对于较小的页面,增加大小以减少开销。
在您的部署中考虑Magick.NET。 它携带ImageMagick本机二进制文件,增加了包大小并带来了本机依赖性足迹。
选项B:LibTiff.NET(完全托管,无本机依赖)
一个完全托管的替代方案,在无解码或重新编码步骤下复制页面。当本机依赖性足迹或精确像素/压缩保真度很重要时很有用。
先决条件:
- 在.NET项目中,使用IronOCR(
IronTesseract)。 BitMiracle.LibTiff.NET(安装命令如下)。- 此处使用的LibTiff类型位于
BitMiracle.LibTiff.Classic命名空间中。
1. 添加LibTiff.NET包:
dotnet add package BitMiracle.LibTiff.NET
2. 添加TiffPageSplitter助手:它在原始条带或瓷砖级别复制每个页面,因此像素数据和压缩完全保留,没有解码或重新编码。 它一次流式传输一个页面,因此峰值内存大约为一个块而不是整个文件,并且它产生多页块,每个块保持在尺寸上限以下。
/// <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;
}
}
助手在原始条带或瓷砖级别复制每个页面,因此像素数据和压缩正好继承。 由于页面一次流式传输,因此峰值内存围绕一个块。
3. OCR每个块:迭代SplitTiffToChunks并使用OcrInput.LoadImage(byte[])加载每个字节数组,而不是使用文件路径,因此没有超过限制的内容到达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++;
}
根据您的数据调整maxPagesPerChunk和maxChunkBytes。 如果解码后的块接近 2 GB 或内存紧张,请降低它们; 通过在较小页面上增加页数以减少开销。
在两者之间选择
- 选项A(Magick.NET): 设置更快且无需自定义助手代码,但携带ImageMagick本机二进制文件(增加包大小和部署足迹),并对每个页面进行解码然后重新编码。
- 选项B(LibTiff.NET): 完全托管,无本机依赖,复制页面到原始条带/瓷砖层次而无解码或重新编码步骤(精确保留原始压缩和像素数据),并逐页流式传输以降低峰值内存。 它需要更多的设置代码,并且只携带助手明确列出的TIFF标签。
注意事项和限制
- 2 GB的上限是IronOCR的
AnyBitmap(由32位整数索引的单个缓冲区)的架构限制,而不是操作系统或可用内存问题。 本机逐页TIFF流没有解决该问题,直到2026.8.1。 - 在修复之前的版本中,当文件太大时,
OcrInput.LoadImage(filePath)返回零加载页而不是抛出明确的错误。 这种静默失败是一个已知问题,计划提供更清晰的异常。 分块通过使每个输入保持在限制以下来规避它。 - LibTiff.NET拆分器仅携带
ScalarIntTags和ScalarDoubleTags中列出的TIFF标签。 如果您的TIFF使用未覆盖的标签,例如ICC配置文件或用于alpha通道的EXTRASAMPLES,请扩展这些列表,否则原始复制的字节可能会被误解。 maxChunkBytes根据编码(压缩)大小进行衡量,这只是一个便宜的代理。 解码后的大小可能要大得多,因此请根据您的实际页面验证上限。 默认值为1.5 GB,以便在2 GB限制下留有余量。
参考文献
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。