大於 2 GB 的 TIFF 檔案在 IronOCR 中無法載入

Curtis Chau
Curtis Chau
已更新: 2026年10月19日

大於約 2 GB 的 TIFF 檔案無法載入,圖像永遠無法到達 OCR。

Loaded pages: 0
Text
請注意: 此限制已在 IronOCR 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
SHELL

將 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++;
}
C#

根據您的數據調整 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
SHELL

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;
    }
}
C#

幫助器在原始條帶或切塊級別上複製每個頁面,因此像素數據和壓縮可以完全保存。 峰值內存保持在一個塊左右,因為頁面一次只流式傳輸一個。

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++;
}
C#

為您的數據調整 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 配置檔或 EXTRASAMPLES 的 alpha 通道,請延展這些列表,否則原始複製的位元可能被誤譯。
  • maxChunkBytes 是根據編碼(壓縮)大小測量的,這只是一個廉價的代理。 解碼大小可能大得多,因此請對照實際頁面驗證上限。 默認為 1.5 GB,以留出在 2 GB 限制以下的空間。
警告: 單頁大於上限始終允許單獨通過,因此 解碼後一個非常大的頁面仍然可超過 2 GB

參考

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

閱讀更多

準備好開始了嗎?

NuGet 下載次數 6,411,693版本:2026.11剛剛發布