Recursive AI

Split a multipage TIFF in C#

All oneimage recipes

Load the TIFF, loop over Frames, and save each page with Frames[i].ToImage().Save(...). Each page can be written as a TIFF, PNG, JPEG or WebP, resized first if you like. The program below splits a three-page fax (CCITT Group 3) from the test files of the Pillow project.

Terminal
dotnet new console -o SplitTiff && cd SplitTiff
dotnet add package RecursiveAI.OneImage --version 1.10.4
repo=https://raw.githubusercontent.com/python-pillow/Pillow/main
curl -L -o fax.tif $repo/Tests/images/total-pages-zero.tif

OneImage needs the .NET 10 SDK. Put this in Program.cs and run dotnet run:

C#
using OneImage;
 
// Identify reads only the page directories: nothing is decoded.
ImageInfo info = Image.Identify("fax.tif");
Console.WriteLine($"fax.tif: {info.Frames.Count} pages");
 
Image tiff = Image.Load("fax.tif");
for (int i = 0; i < tiff.FrameCount; i++)
{
    Image page = tiff.Frames[i].ToImage();   // one page as an ordinary image
    page.Save($"page-{i + 1}.tif");
    page.Save($"page-{i + 1}.png");
    Console.WriteLine($"page {i + 1}: {page.Width}x{page.Height}, {page.Format}");
}
Text
fax.tif: 3 pages
page 1: 1728x2156, Gray/U8/None
page 2: 1728x2156, Gray/U8/None
page 3: 1728x2156, Gray/U8/None

Each page is decoded when it is saved. Pages can differ in size and color type; each keeps its own. Fax pages are 1-bit in the file and load as 8-bit gray. Image.Load("fax.tif").Frames[1].ToImage() gets one page without decoding the others.

Recompress or convert every page

Saving the loaded image writes every page again, and operations apply to every page:

C#
using OneImage;
 
Image tiff = Image.Load("fax.tif");
 
tiff.Save("fax-deflate.tif", new SaveOptions
{
    EncoderOptions = new TiffEncoderOptions { Compression = TiffCompression.Deflate },
});
tiff.Resize(width: 864).Save("fax-half.tif");   // every page at half width
 
foreach (string file in new[] { "fax.tif", "fax-deflate.tif", "fax-half.tif" })
{
    long kb = new FileInfo(file).Length / 1024;
    Console.WriteLine($"{file}: {Image.Identify(file).Frames.Count} pages, {kb} KB");
}
Text
fax.tif: 3 pages, 94 KB
fax-deflate.tif: 3 pages, 114 KB
fax-half.tif: 3 pages, 227 KB

Limits

  • Fax compression is read, not written. OneImage reads CCITT G3 and G4 but writes TIFF with no compression, LZW, Deflate or PackBits, so a re-saved fax is larger than the original.
  • JPEG and BMP hold one image. Saving the whole TIFF to .jpg writes the first page only; loop over Frames as above.
  • Not every TIFF variant loads. Signed and 64-bit samples, plain YCbCr and CIELab are rejected with an error. Strips, tiles, BigTIFF, LZW, Deflate, PackBits, JPEG, CCITT, 1- to 16-bit and float samples, and CMYK are read.
  • Untrusted files are bounded: at most 1,000 pages and 65,535 pixels a side by default, checked from the headers.

To make a multipage TIFF from a PDF, see Convert a PDF to TIFF. The TIFF reader and writer are described in the guide.