IronOCR에서 2GB보다 큰 TIFF 파일이 로드되지 않음

Curtis Chau
Curtis Chau
업데이트됨: 2026년 10월 19일

약 2GB보다 큰 TIFF 파일은 로드에 실패하며, 이미지가 OCR에 도달하지 않습니다.

Loaded pages: 0
Text
유의 사항: 이 제한은 IronOCR 2026.8.1에서 해결되었습니다. 해결을 위해 해당 버전 또는 이후 버전으로 업그레이드하세요. 아래의 단계는 이전 버전을 사용하는 사용자에게 해당됩니다.

IronOCR는 내부의 AnyBitmap 유형을 통해 단일 인메모리 버퍼에 이미지 입력을 로드합니다. 해당 버퍼는 32비트 정수로 색인화되어 있어 시스템 메모리가 얼마나 많은지와 상관없이 약 2GB에서 제한됩니다. 그 제한을 약간 넘는 TIFF는 유지할 수 없어 로드에 실패합니다.

OcrInput.LoadImage(filePath)는 내부적으로 AnyBitmap를 생성하고 전체 이미지를 하나의 버퍼에 구현합니다. 수정 이전 버전에서는 이 호출이 명확한 예외를 던지지 않고 0개의 로드된 페이지를 반환합니다. 그러한 무음 실패는 알려진 문제이며, 더 나은 예외 처리가 계획되어 있습니다. 단일 버퍼 디자인은 구조적 제한입니다; 파일 전체를 버퍼링하는 것을 피할 수 있는 네이티브 페이지별 TIFF 스트리밍은 2026.8.1 전에 사용할 수 없었습니다.

환경

  • 언어/런타임: .NET (크로스 플랫폼, 이 제한은 런타임 제한이며, 운영체제에 특화된 것이 아닙니다.)

버전 메타데이터

  • 발견된 버전: 2026.5.2
  • 해결 버전: 2026.8.1

해결책

추천: 이 제한이 해결된 IronOCR 2026.8.1 또는 이후 버전으로 업그레이드하세요.

아직 업그레이드할 수 없다면, TIFF를 2GB 이하의 청크로 분할하고 OcrInput.LoadImage(byte[])로 각 청크를 로드하여, 한계 이상의 것이 AnyBitmap에 도달하지 않도록 하십시오. 아래 두 가지 접근 방법이 있습니다.

옵션 A: Magick.NET (가장 간단한 설정)

IronOCR에 전달하기 전에 TIFF를 분할하려면 Magick.NET을 추가하십시오. 프로젝트에 맞는 변형을 선택하십시오 (Q8/Q16, AnyCPU/x64).

dotnet add package Magick.NET-Q16-AnyCPU
SHELL

TIFF를 MagickImageCollection로 열어 페이지 수에 따라 2GB 이하의 청크로 분할하고, 각 청크를 바이트 배열로 변환한 후, 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를 조정하십시오. 청크가 2GB에 접근하거나 메모리가 빡빡할 경우 낮추십시오; 작은 페이지에 대해서는 오버헤드를 줄이기 위해 올리십시오.

배포 시 Magick.NET을 고려하십시오. ImageMagick 네이티브 바이너리를 제공하므로 패키지 크기가 늘어나고 네이티브 종속성 발자국을 추가합니다.

옵션 B: LibTiff.NET (완전히 관리되며, 네이티브 종속성 없음)

디코드나 재인코딩 단계 없이 페이지를 원시 레벨에서 복사하는 완전 관리 대안입니다. 네이티브 종속성 발자국 또는 정확한 픽셀/압축 충실도가 중요한 경우 유용합니다.

전제조건:

  • IronOCR (IronTesseract)을 포함한 .NET 프로젝트.
  • 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를 조정하십시오. 디코딩 후 청크가 2GB에 근접하거나 메모리가 부족한 경우 하향 조정하십시오; 오버헤드를 줄이기 위해 더 작은 페이지에 대해 페이지 수를 늘리십시오.

두 가지 중 선택하기

  • 옵션 A (Magick.NET): 설정이 더 빠르고 커스텀 헬퍼 코드가 필요 없지만, ImageMagick 네이티브 바이너리를 제공하여 패키지 크기와 배포 발자국을 늘리고 각 페이지를 디코드하고 재인코딩함.
  • 옵션 B (LibTiff.NET): 네이티브 종속성 없이 완전히 관리되며, 디코드나 재인코딩 단계 없이 원시 스트립/타일 레벨에서 페이지를 복사(원래 압축과 픽셀 데이터를 정확히 보존)하고, 메모리 피크를 낮추기 위해 한 번에 하나의 페이지를 스트리밍합니다. 더 많은 설정 코드가 필요하며 헬퍼가 명시적으로 나열하는 TIFF 태그만 전송됩니다.

참고 사항 및 제한 사항

  • 2GB 한계는 IronOCR의 AnyBitmap (32비트 정수로 색이 되는 단일 버퍼)의 구조적 제한이지, 운영체제나 사용 가능 메모리 문제는 아닙니다. 네이티브 페이지별 TIFF 스트리밍은 2026.8.1까지 그 문제를 해결하지 못했습니다.
  • 수정 이전 버전에서는, OcrInput.LoadImage(filePath)은 파일이 너무 큰 경우 명확한 오류를 던지는 대신 0개의 로드된 페이지를 반환합니다. 이 무음 실패는 알려진 문제이며 더 나은 예외 처리가 계획되어 있습니다. 청크 처리를 통해 모든 입력을 제한 이하여로 유지하여 이를 우회합니다.
  • LibTiff.NET 분할기는 ScalarIntTags와 ScalarDoubleTags에 나열된 TIFF 태그만 가지고 갑니다. 귀하의 TIFF가 거기에 포함되지 않은 태그를 사용하는 경우, 예를 들어 ICC 프로필이나 알파 채널을 위한 EXTRASAMPLES을 사용하는 경우, 그 목록을 확장하셔야 하며, 그렇지 않으면 원시로 복사된 바이트가 잘못 해석될 수 있습니다.
  • maxChunkBytes은 인코딩(압축)된 크기를 기준으로 측정되며, 이는 오직 값싼 대리인일 뿐입니다. 디코딩된 크기가 훨씬 클 수 있으므로, 실제 페이지에 대한 한계를 검증하세요. 기본값은 2GB 제한 아래에서 여유 공간을 남기기 위해 1.5GB입니다.
경고: 단일 페이지가 제한보다 크더라도 단독으로 허용되므로, 매우 큰 페이지 하나가 디코딩되면 여전히 2GB를 초과할 수 있습니다.

참고 문헌

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

더 읽기

시작할 준비 되셨나요?

NuGet 다운로드 수 6,411,693버전:2026.11방금 출시