TIFF and BigTIFF

edit

TIFF is the format of scanned documents, multi-page files and imaging pipelines. TiffEncoder writes every page without loss by default, compressed with Deflate, in a layout that follows the pixel format. It needs a seekable destination, except for a page that is not compressed.

What is read and written

ReadingWriting
ContainerClassic TIFF and BigTIFF, both byte orders, strips and tiles, chunky samples and separate planes, multi-page documentsClassic TIFF (default) or BigTIFF, both byte orders, strips or tiles, chunky samples or separate planes, multi-page documents
SamplesBilevel, 2, 4, 8 and 16-bit gray, gray and alpha, RGB, RGBA, palette, YCbCr; signed 8 and 16-bit samples; 16, 24 and 32-bit floating-point samples; 8 and 16-bit CMYK as CMYK pixels or with a color conversion; CIE, ICC and ITU L*a*b*, or their lightness only, with a color conversionGray, gray and alpha, RGB and RGBA at 8 or 16 bits, CMYK at 8 or 16 bits (lossless compressions), bilevel, palette, 32-bit floating-point
CompressionNone, Deflate, LZW, PackBits, CCITT (modified Huffman, Group 3, Group 4), JPEG, old-style JPEG, JPEG 2000; the bits of each byte in either order (FillOrder), except in JPEG and JPEG 2000 dataNone, Deflate (default), LZW, PackBits, CCITT for bilevel pages, JPEG
MetadataResolution, orientation, ICC profile, XMPThe same
Reduced sizeThe reduced-resolution images of the first page (pyramids)-

Image.Load reads the first page. Floating-point pages load as RgbaHalf (16 bits) or RgbaFloat, and gray ones as GrayHalf, LaHalf, GrayFloat or LaFloat. The encoder writes a floating-point image whose pixels are gray as one sample (two with alpha).

Write a document of several pages

A document is an ImageCollection of pages, whose sizes and pixel formats may differ. Image.Save writes a document of one page:

public static Size WriteAndReadTiffDocument(string inputPath, string documentPath)
{
    using (var pages = ImageCollection.Create(ImageCollectionKind.Pages))
    {
        using var source = Image.Load(inputPath);
        using var first = source.CloneFrame(0); // a page is a still image, never an animation frame
        using var second = first.Clone();
        second.Resize(new ResizeOptions(first.Width / 2, first.Height / 2));

        // Add copies the image: the caller keeps and disposes its own
        pages.Add(first);
        pages.Add(second);
        pages.Save(documentPath, new TiffEncoder { Compression = TiffCompression.Deflate });
    }

    // Loading reads the directory structure only: the pixels of a page are read when that page is decoded
    using var document = ImageCollection.Load(documentPath);
    using var page = document[1].Decode();
    return page.Size; // the second page keeps its own size, never the first one's
}

Loading a collection reads the structure of the document only; a page is decoded when you call Decode. See Pages and representations. An animated image is rejected: the pages of a document are not animation frames.

Save a scanned document

A bilevel page stores one bit per pixel, which the CCITT compressions of fax machines code compactly; Group 4 is the smallest. Every pixel must be opaque and exactly black or exactly white, so binarize the scan first:

public static void SaveScanAsBilevel(string inputPath, string tiffPath, string pbmPath)
{
    using var page = Image.Load(inputPath);

    // Sauvola's threshold follows uneven lighting: each pixel is compared with the mean and the contrast of the
    // 31 x 31 pixels around it, so the text becomes black and the paper white, even in a shadow. The pixels are now
    // exactly black or white, in the same pixel format.
    page.Threshold(new ThresholdOptions { Method = ThresholdMethod.Sauvola, WindowSize = 31 });

    // A bilevel page with Group 4 compression, the usual format of scanned documents
    page.Save(tiffPath, new TiffEncoder { PixelLayout = TiffPixelLayout.Bilevel, Compression = TiffCompression.CcittGroup4 });

    // A portable bitmap: one bit per pixel
    page.Save(pbmPath, new PnmEncoder { PixelLayout = PnmPixelLayout.Bitmap });
}

See Binarization. A bilevel page loads back as Gray8, with one bit per component.

Write separate planes

By default, the samples of a pixel are stored side by side (chunky, PlanarConfiguration 1). SeparatePlanes stores each sample in a plane of its own (PlanarConfiguration 2): the strips or tiles of the red samples, then those of the green, blue and alpha samples (or the cyan, magenta, yellow and black inks). Some imaging pipelines expect this layout, and it can compress better, because each plane is predicted and compressed on its own:

public static void SaveTiffInSeparatePlanes(string inputPath, string tiffPath)
{
    using var image = Image.Load(inputPath);

    // One strip set of red samples, then of green, blue and alpha samples (PlanarConfiguration = 2), each plane
    // predicted and compressed on its own
    image.Save(tiffPath, new TiffEncoder { SeparatePlanes = true, Predictor = TiffPredictor.HorizontalDifferencing });
}

Every layout, compression (but Jpeg), predictor, strip and tile setting works with separate planes, in single-page saves and in documents. A page of one sample per pixel (gray, bilevel, palette) has a single plane: it is the same file either way, and is written as chunky, which more readers accept.

Write to a stream that cannot seek

A directory stores the offsets of the strips it describes, so the directory of a compressed page is written after its strips, and the pointer to it is patched afterward: a compressed page needs a seekable destination. The strips of an uncompressed page (None) have known lengths, so its directory is written before them and nothing is patched: a one-page uncompressed document is written forward only, to any stream, such as a network stream or the body of an HTTP response. A document of several pages links each directory to the next one, so it still needs a seekable destination.

Pyramids

A large image is often stored with reduced-resolution versions of itself, so that a viewer can show it at any zoom level: a Cloud Optimized GeoTIFF file stores them after the image (overviews), and slide scanners, OME-TIFF and libvips store them in its SubIFDs tag. ImageDecodeOptions.TargetSize reads the smallest of them that is still at least the target size, and ScaleDenominator the one at that scale, without reading the full image:

  • An image is used when it is marked as a reduced-resolution image (NewSubfileType bit 0, or SubfileType 2) and not as a transparency mask, its size is the size of the page divided by a power of two (rounded down or up), and its pixels have the format and the color model of the page. The other images, and those that cannot be read, are ignored.
  • The image has the size of the reduced-resolution image and the metadata of the page (orientation, color profile).
  • A Region is in pixels of the full page: the image holds the pixels of the reduced-resolution image that cover it.
  • Image.Identify reports the size of the page. An ImageCollection lists every image of the file, the reduced-resolution ones included, and decodes each at full resolution.

See Decode a smaller image.

Options

OptionWhat it doesDefault
CompressionNone, Deflate, Lzw, PackBits, CcittModifiedHuffman, CcittGroup3, CcittGroup4 or Jpeg (lossy)Deflate
PixelLayoutAuto follows the pixel format; Bilevel writes one bit per pixel; Indexed writes a palette of at most 256 colorsAuto
JpegQualityThe quality of Jpeg compression, as JpegEncoder.Quality90
JpegChromaSubsamplingThe chroma subsampling of Jpeg compressionAuto (4:2:0)
BigTiffWrites a BigTIFF (64-bit offsets), which fewer readers acceptfalse
BigEndianWrites big-endian instead of little-endian files; the pixels are the samefalse
RowsPerStripThe rows of a strip; 0 chooses strips of about 64 KiB of samples0
TileWidth and TileHeightWrite tiles of this size (multiples of 16) instead of strips, so that readers can decode a region of a large page; the tiles of the right and bottom edges are padded0 (strips)
SeparatePlanesStores each sample in a plane of its own (PlanarConfiguration 2) instead of the samples of a pixel side by sidefalse
PredictorHorizontalDifferencing stores the difference of each 8- or 16-bit sample from its left neighbor, which usually makes photographs, gradients and screenshots smaller with Deflate and LZW (the only compressions it is accepted with)None
MetadataHandlingWhat to do with metadata TIFF cannot storeStrict

Exact or rejected

TiffEncoder has no background color, no bit-depth reduction and no color reduction: the bilevel and palette layouts store a page exactly or reject it with an UnsupportedImageFeatureException before anything of the page is written.

  • Bilevel rejects a pixel that is not opaque and exactly black or white; Indexed rejects a page with more than 256 colors or a pixel that is not opaque.
  • The CCITT compressions require PixelLayout = Bilevel, and Jpeg requires Auto: another combination throws an ArgumentException. So does horizontal differencing with another compression than Deflate or LZW or another layout than Auto, a tile size without the other one, and tiles or separate planes with Jpeg.
  • Jpeg is the only lossy compression. It stores 8-bit samples without alpha: a 16-bit pixel format or a pixel that is not opaque is rejected.

Pitfalls

  • The destination must be seekable, unless the document is one uncompressed page: a directory stores the offsets of the strips or tiles it describes, which are only known once they are compressed. A non-seekable stream is rejected before anything is written; paths are always seekable.
  • EXIF blocks and text entries are not written: they follow MetadataHandling, which rejects them by default.
  • Floating-point pages are written as 32-bit floats with PixelLayout = Auto and any compression but Jpeg. A floating-point page without an ICC profile is read as linear light, so the image must be labeled ColorTransferFunction.Linear (the label of a new floating-point image) or have an ICC profile. See Pixel formats.
  • CMYK pages without alpha load as Cmyk32 or Cmyk64 pixels with Image.Load<Cmyk32>, and CMYK images are written as separated pages (PhotometricInterpretation 5, InkSet 1) with PixelLayout = Auto and a lossless compression. An untyped load, and a page with alpha, need ImageDecodeOptions.CmykConversion, which converts the page to RGB. See Color management.
  • CIE L*a*b* pages (CIELab, ITULab, and 8-bit ICCLab) load only with ImageDecodeOptions.CieLabConversion, which converts their colors, relative to the WhitePoint of the page (D50 without one), to an RGB profile, sRGB by default. Colors outside its gamut are clipped or mapped, as CieLabConversionOptions.Transform says. Identification reports ImageColorModel.CieLab. A page that stores only the lightness (one sample, and an optional alpha sample) has neutral colors: a* and b* are 0. The samples of ITULab (TIFF-FX, RFC 2301) cover the ranges of its Decode tag, by default 0 to 100 for L*, -85 to 85 for a* and -75 to 125 for b*; they are read uncompressed, with the lossless compressions, or with JPEG compression, whose components are the samples. 16-bit ICCLab pages are rejected: the versions of the ICC specification encode them differently.
  • Old-style JPEG pages (TIFF 6.0 compression 6) are read as libtiff reads them: with the header of JPEGInterchangeFormat or with the tables of the JPEGQTables, JPEGDCTables and JPEGACTables tags, each strip or tile is decoded as a JPEG datastream of its own. Only the baseline process is read, with 8-bit or 12-bit samples (12-bit samples are decoded scaled to 16 bits, as with JPEG compression); the lossless process and separate planes with an interchange format are rejected.
  • YCbCr data in separate planes is read uncompressed or with the lossless compressions. The blocks of the chroma planes of subsampled data cover the area of the luma blocks with one sample for each YCbCrSubSampling group of pixels, as TIFF 6.0 describes them, and their samples are replicated over the group, as for chunky data. libtiff does not read subsampled planes. JPEG-compressed planes are rejected.
  • The orientation of a page is reported, never applied: call AutoOrient.
  • ImageDecodeOptions.Region reads only the strips or the tiles that an area meets, each one whole: a page of one strip is still decompressed whole, so write large pages with tiles for viewports. See Decode an area.
  • 64-bit floating-point samples are rejected with an UnsupportedImageFeatureException. Compressed data is never repaired: a damaged strip is an InvalidImageContentException, never a page completed with white.
  • Some writers store one BitsPerSample value for all the samples, extra values, or no byte counts for a page of one uncompressed strip. These files are rejected by default; the lenient decoding reads them the way libtiff and Apple ImageIO do.