Almost everyone who writes a TIFF reader tries this patch once. The file carries TileOffsets instead of StripOffsets, the two arrays look identical, so you point the strip fields at the tile arrays and ship it. The page then decodes at exactly the right width and height with every row smeared into diagonal stripes. Tiled layouts, BigTIFF and oversized rasters each need handling of their own, and the PDFlibPas built-in TIFF decoder for Delphi gives them that: a dedicated reader for tiled and 64-bit layouts, one 256 MiB decode budget per page, and a named reason in TPDFTIFF.LastError for every refusal
The header hides a smaller version of the same trap. A BigTIFF opens with the same II or MM as any office scan, and of its first four bytes exactly one differs: the magic number reads 43 instead of 42. Below, each layer gets the same treatment: what the decoder checks, what it reports, and what your code should do next
Why does an II or MM header not mean classic TIFF?
The byte-order marker is shared by both dialects, so it proves nothing about the layout behind it. TIFF 6.0 defines the header as two bytes of byte order followed by the 16-bit magic number 42 and a 32-bit offset to the first image directory. BigTIFF keeps the same II or MM marker, switches the magic to 43, declares an offset size of 8 and stores every offset and count as a 64-bit value. A loader written as FValidTIFF := PopWord = 42 is correct about classic TIFF and still unhelpful, because it folds a perfectly valid BigTIFF and a renamed JPEG into the same silent False
PDFlibPas reads the two fields separately and reports each failure in its own words. A file shorter than four bytes gets "The TIFF header is incomplete", a bad marker gets "The TIFF byte-order marker is invalid", an unknown magic gets "The TIFF magic value is invalid", and an input larger than the in-memory budget gets "TIFF input exceeds the 256 MiB byte budget". For magic 43 the decoder walks the 64-bit directory chain in either byte order, insists on the declared 8-byte offset size, and keeps offsets and counts in 64-bit integers until they have been range-checked against the actual file. TPDFTIFF.IsBigTIFF then tells you which dialect the file came from, even after the page has been handed to the regular codecs
Alignment is where real files part ways with the tidy version of the format. BigTIFF writers are expected to keep directories and out-of-line values on 8-byte boundaries, yet encoders in the wild emit directories aligned only to two bytes. We read every integer byte by byte, so alignment has no performance meaning for us, and rejecting those files would have been pedantry. The decoder accepts word alignment, still refuses odd addresses, and keeps every span, count and loop check in place
An intake triage step that logs the dialect and the exact reason takes a few lines:
var
Tiff: TPDFTIFF;
Page: Integer;
begin
Tiff := TPDFTIFF.Create;
try
Tiff.LoadFromFile('inbox\slide-0417.tif');
if not Tiff.ValidTIFF then
raise Exception.CreateFmt('TIFF rejected (BigTIFF: %s): %s',
[BoolToStr(Tiff.IsBigTIFF, True), Tiff.LastError]);
for Page := 1 to Tiff.PageCount do
Writeln(Format('page %d: %d x %d, %d bits, %d samples',
[Page,
Tiff.PageInfo[Page].Width,
Tiff.PageInfo[Page].Height,
Tiff.PageInfo[Page].BitsPerSample,
Tiff.PageInfo[Page].SamplesPerPixel]));
finally
Tiff.Free;
end;
end;
Tiles are a grid with padding at the edges
The patch from the opening deserves a closer look. Tag 324 (TileOffsets) and tag 325 (TileByteCounts) are arrays of file offsets and byte counts, structurally identical to StripOffsets and StripByteCounts, so pointing the strip fields at them compiles on the first try. The output is wrong. The tiled-image section of TIFF 6.0 describes a two-dimensional grid whose TileWidth and TileLength must be multiples of 16, where every tile is encoded at full size and the blocks on the right and bottom edges simply carry padding past the image boundary. A strip decoder walks that data with the wrong row stride and never notices. You get a page with correct dimensions and scrambled content
In PDFlibPas, any directory carrying tile fields goes through the same directory reader that handles BigTIFF. It requires tile dimensions that are positive multiples of 16, refuses a directory that mixes strip and tile fields, checks that offsets, byte counts and image dimensions agree, and validates every compressed tile before the page is accepted. The budget is charged for the full padded grid. Suppose a file declares a 20 by 20 pixel RGB image with a single 65,520 by 65,520 tile: charged at full padded size, that tile works out to roughly 12 GiB of decoded samples, far past the 256 MiB budget, so the directory is refused before any tile is decompressed
Padding is the second trap, and it bites people who got the grid right. Decoding a short edge tile at its visible size and stretching it looks plausible until the codec parameters disagree: CCITT Columns and Rows, and the Columns value of an LZW or Deflate predictor, all have to describe the full tile, because that is what the encoder compressed. PDFlibPas places every tile at its full encoded size and clips the right and bottom padding when the image is drawn. A file with a single tile takes the same clipping route, otherwise an image smaller than one tile would be stretched to fill it. JPEG-compressed tiles add one more wrinkle: the JPEG segment lengths and the SOF dimensions are always big-endian, whatever the surrounding TIFF says, and the SOF size has to match the full tile rather than the visible region
One dimension clamp is not a memory budget
Clamping width and height to 65,535 each is necessary and nowhere near enough, because allocation follows a product. RowsPerStrip * Width * SamplesPerPixel can overflow 32-bit arithmetic long before either factor hits its own limit, and even without overflow it can name a buffer no server should allocate. PDFlibPas computes row bytes in Int64 and enforces three ceilings together: 65,535 per dimension, 32 color components and 256 MiB of decoded bytes. The check is short enough to quote:
const
PDFLIB_TIFF_MAX_IMAGE_DIM = 65535;
PDFLIB_TIFF_MAX_COLOR_COMPONENTS = 32;
PDFLIB_TIFF_MAX_DECODED_IMAGE_BYTES = 256 * 1024 * 1024;
// excerpt from the library's internal per-page check (not a public API)
BitsPerPixel := Int64(P.BitsPerSample) * P.SamplesPerPixel;
RowBytes := (Int64(P.Width) * BitsPerPixel + 7) div 8;
if (RowBytes < 1) or
(RowBytes > PDFLIB_TIFF_MAX_DECODED_IMAGE_BYTES) or
(Int64(P.Height) > PDFLIB_TIFF_MAX_DECODED_IMAGE_BYTES div RowBytes) then
Exit(False);
DecodedBytes := RowBytes * P.RowsPerStrip;
if (DecodedBytes < 1) or
(DecodedBytes > PDFLIB_TIFF_MAX_DECODED_IMAGE_BYTES) or
(DecodedBytes > MaxInt) then
Exit(False);
Three details matter more than the constants. The height test divides instead of multiplying, so the oversized product is never formed at all. A RowsPerStrip below 1 or above the image height is normalized to the height first, which is the single-strip reading TIFF 6.0 already implies and which stops a hostile tag from inflating the strip buffer. And the same check runs more than once: when the tags are parsed, and again right before each decoder starts on a page, so no route through TPDFTIFF reaches pixel data without meeting the same limits. Never size an array from a count read out of the file until that count has been checked against the bytes actually present; the same rule drives how PDFlibPas handles untrusted PDF object graphs
What should a caller check before reading PageInfo?
Check ValidTIFF first, then PageCount, and only then index PageInfo. A rejected file can leave PageCount at zero, and PageInfo only returns a meaningful record for an index between 1 and PageCount, so an error handler that reads resolution or sample counts on its way to reporting the failure ends up logging noise. The import side follows the same order: TPDFlib.GetImagePageCount returns zero unless the file passes as a valid TIFF with at least one page, and the Options argument of AddImageFromFile is the 1-based page number for a multipage TIFF
const
Src = 'inbox\scan-0417.tif';
var
Pdf: TPDFlib;
Pages, I, ImageID: Integer;
begin
Pdf := TPDFlib.Create;
try
Pages := Pdf.GetImagePageCount(Src);
if Pages < 1 then
raise Exception.Create('Not importable: ' + Src);
Pdf.NewDocument;
Pdf.SetOrigin(1); // top-left coordinates
for I := 1 to Pages do
begin
if I > 1 then
Pdf.NewPage;
ImageID := Pdf.AddImageFromFile(Src, I);
if ImageID = 0 then
raise Exception.CreateFmt('Page %d of %s did not import', [I, Src]);
Pdf.SelectImage(ImageID);
Pdf.DrawImage(0, 0, 595, 842);
end;
Pdf.SaveToFile('scan-0417.pdf');
finally
Pdf.Free;
end;
end;
Skipping the page and carrying on is tempting, and we think it is the wrong default: the PDF comes out one sheet short with nothing in the log, which is exactly how a duplex scan batch that gets collated and interleaved ends up with every later sheet in the wrong position. Fail the document and keep the original TIFF for whoever looks at it next
The two entry points also differ in scope. LoadFromFile validates every page, so a single page the decoder cannot handle rejects the whole file. When you want to know which page is the problem, load one page at a time with LoadFromStream, whose second argument is a zero-based page index:
function TiffPageVerdict(const FileName: string; PageNo: Integer;
out Reason: string): Boolean;
var
Tiff: TPDFTIFF;
FS: TFileStream;
begin
Tiff := TPDFTIFF.Create;
try
FS := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Tiff.LoadFromStream(FS, PageNo - 1); // zero-based page index
finally
FS.Free;
end;
Result := Tiff.ValidTIFF and (Tiff.PageCount > 0);
Reason := Tiff.LastError;
finally
Tiff.Free;
end;
end;
The import path applies a few checks of its own on top of TPDFTIFF. The authoritative answer for a given page is an AddImageFromFile result greater than zero
Codec traps between the TIFF and PDF specifications
A good share of TIFF payloads can go into the PDF without being decoded, because their compression lines up with a standard PDF filter (ISO 32000-1 §7.4.4 for LZW and Flate, §7.4.6 for CCITT fax). PackBits looks like the easiest pass-through of all, since PDF's RunLengthDecode in §7.4.5 uses almost the same packet format. Almost. In TIFF PackBits a length byte of 128 is a no-op; in RunLengthDecode the same byte means end of data. Copy a PackBits strip straight into a RunLength stream and any no-op packet silently truncates the rest of the image. PDFlibPas walks every packet, drops the no-ops, keeps literal 128 values inside literal runs untouched, merges the strips and appends exactly one terminator
JPEG-in-TIFF forces an explicit choice. TIFF Technical Note 2 requires the YCbCrSubSampling tag to match the sampling factors in the JPEG frame, and real files routinely get it wrong or leave it out, which means the default of 2,2. libtiff quietly corrects the tag from the first strip's SOF marker and only complains when later blocks disagree. We went further in the same direction: each block is upsampled using the sampling factors in its own frame, and a mismatched tag is not an error. Raising one would reject files that libtiff and every common viewer display correctly, and we would rather not be the only tool in the chain that refuses a file the user can see is fine
Codecs cover CCITT Modified Huffman, Group 3 one- and two-dimensional and Group 4, LZW, Deflate, PackBits and JPEG, where the JPEG side goes past 8-bit baseline and progressive into 12-bit Huffman, arithmetic coding and lossless. Photometrics cover WhiteIsZero, BlackIsZero, RGB, palette, CMYK, YCbCr, CIELab and ICCLab, with chunky or separate planes, alpha and extra channels, and Predictor 1, 2 and 3. Floating-point samples are mapped from their SMinSampleValue to SMaxSampleValue range, or 0 to 1 when those tags are absent, into clamped 16-bit values, so the image imports while its HDR headroom stays behind
Why we kept a hand-written decoder instead of libtiff
The deciding factor was platform reach. The TIFF front end is about 6,100 lines of Object Pascal across four units: the parser, the BigTIFF and tile directory reader, sample conversion, and the JPEG validator and decoder it leans on. All of it compiles wherever the compiler goes, which for PDFlibPas means Win32, Win64, macOS, iOS, Android and FPC on Linux. libtiff 4.7.1 is around 30,000 lines of C, and every one of those targets would need its own C build and linker setup. That trade buys a mature codebase and costs a shrinking platform list, and for a Delphi component we think the platform list matters more
For a scanned-document pipeline, run TPDFTIFF as a gate in front of the import, log LastError verbatim whenever ValidTIFF is false, and keep IsBigTIFF in the same log line. Pages are read from the main directory chain, so for a pyramidal slide or map, export the resolution level you actually want as the main image, within 65,535 pixels per side, before it reaches the decoder. Strips compressed with PixarLog or SGILog need converting upstream to one of the codecs listed above before import. Formats outside TIFF entirely take a different route through the AVIF, HEIF and JPEG XL image input path
The TIFF import, the other image formats and the rest of the PDF API for Delphi and C++Builder are covered on the PDFlibPas product page