Technical Article

Shrink PDFs by Merging Near-Identical Images in Delphi

Run an exact deduplication pass over a merged batch of scanned letters and the image counter can come back at zero while every page plainly carries the same letterhead. Pull two of those logo streams out and the reason is right there in the bytes: one was DCT-encoded at one quality setting, another at a slightly lower one, a third came through a different scanner driver with its own Huffman tables. Same picture. Three unrelated byte strings. Merging them means decoding the pixels and deciding how close counts as the same image, and that decision is where all the risk sits

Comparing decoded pixels through three gates

In PDF Library for Delphi the call is TPDFlib.DeduplicateSimilarImages. It decodes every candidate image, reduces it to a fixed 64 by 64 RGB sample, and merges two images only when three separate thresholds all hold; every reference to the duplicate is then repointed to a single canonical image object. The exact path, DeduplicateResources, never decodes anything and only merges streams whose dictionaries and encoded payloads match byte for byte

The first gate is a 64-bit difference hash built from the sample. The hash reads eight rows spread evenly from the top of the grid to the bottom, and in each row it takes eight pairs of luma-weighted sample points, the two points of a pair sitting about one eighth of the row width apart; each bit records whether the left point of its pair is brighter than the right one, so the hash describes the coarse light-and-dark structure of the image and ignores exact colors. MaxHashDistance is the permitted Hamming distance between two hashes and accepts 0 to 7. The second gate, MaxMeanError, bounds the average absolute difference over all 12,288 sampled channel values (64 × 64 × 3). The third, MaxChannelError, bounds the single largest difference anywhere in the sample. Both error thresholds are integers from 0 to 255

Each gate catches a different kind of change. Recompression produces a small error spread everywhere: the mean stays low, the maximum stays low, the image passes. A watermark stamped into one corner leaves most samples untouched, so the mean barely moves, but the samples that land on the stamp differ by a lot and the maximum-error gate rejects the pair. The structural hash can easily stay identical in that watermark case, which is why a hash-only matcher is the wrong tool for anything you intend to ship

PDF Library for Delphi three thresholds gate the merge of near-identical images: hash distance, mean channel error, and maximum single-channel error
All three gates use decoded pixels — a watermark pair dies at the maximum-error gate while a re-encoded twin sails through

Start every new document class with a dry run. PDF_RESOURCE_DEDUP_DRY_RUN performs the full decode and matching and fills in the statistics, but leaves every reference where it was. The only other flag the method accepts is PDF_RESOURCE_DEDUP_GARBAGE_COLLECT, which removes the duplicate objects once nothing points at them; it has no effect during a dry run

uses
  SysUtils, PDFlibrary;

var
  Lib: TPDFlib;
  Stats: TPDFlibImageSimilarityDedupStats;
begin
  Lib := TPDFlib.Create;
  try
    if Lib.LoadFromFile('scanned-batch.pdf', '') = 0 then
      raise Exception.Create('cannot open scanned-batch.pdf');

    // Hash distance 2, mean error 2, single-channel error 6.
    // Dry run: matching and statistics only, no reference is changed
    Lib.DeduplicateSimilarImages(2, 2, 6, PDF_RESOURCE_DEDUP_DRY_RUN, Stats);
    Writeln(Format('%d scanned, %d would merge, %d bytes of duplicate payload',
      [Stats.ImagesScanned, Stats.ImagesDeduplicated,
       Stats.DuplicatePayloadBytes]));
    Writeln(Format('worst accepted: hash %d, mean %.2f, channel %d',
      [Stats.MaxAcceptedHashDistance, Stats.MaxAcceptedMeanError,
       Stats.MaxAcceptedChannelError]));

    // Same thresholds for real, then drop the orphaned duplicates
    Lib.DeduplicateSimilarImages(2, 2, 6,
      PDF_RESOURCE_DEDUP_GARBAGE_COLLECT, Stats);
    Writeln(Format('%d merged, %d refs repointed, %d objects removed',
      [Stats.ImagesDeduplicated, Stats.ReferencesRepointed,
       Stats.OrphanObjectsRemoved]));
    Lib.SaveToFile('scanned-batch-optimized.pdf');
  finally
    Lib.Free;
  end;
end;

Why do identical-looking images refuse to merge?

Pixels are only compared between images that already agree on everything else. DeduplicateSimilarImages builds a signature from the full image dictionary minus /Length, /Filter and /DecodeParms, the three keys that legitimately change when an image is re-encoded. Dimensions, color space, bit depth, /Mask and /SMask, the /Decode array, /Interpolate, optional content membership and metadata all have to match before the hash is even looked at

That ordering exists because two images can be pixel-identical at 64 by 64 and still behave differently on the page. One with /Interpolate true gets smoothed when a viewer scales it up; the other does not. One that belongs to an optional content group disappears when the user hides that layer. Merge across either boundary and the document gets smaller and wrong

Here is the part that trips people up. Inside that signature, an indirect reference is compared by its object and generation number, and the stream it points to is never opened. Some producers write a fresh ICC profile stream for every image they place, so one image says /ColorSpace [/ICCBased 12 0 R], the next says [/ICCBased 47 0 R], and the two profiles are byte-identical. Soft masks split per page behave the same way. To the perceptual pass those images are semantically different, and no threshold setting will ever merge them

The fix is ordering. DeduplicateResources with its default options covers ICC profiles, image streams, metadata and the other shared stream kinds, so after one exact pass the duplicate profiles collapse into a single object and every image now points at the same number. Running the exact pass first is the order we recommend for every document, and the perceptual pass gets noticeably more to work with afterwards

var
  Exact: TPDFlibResourceDedupStats;
  Similar: TPDFlibImageSimilarityDedupStats;
begin
  // 1. Lossless: identical ICC profiles, soft masks and image streams
  //    collapse to one object each, and orphans are collected
  Lib.DeduplicateResources(PDF_RESOURCE_DEDUP_DEFAULT, Exact);
  Writeln(Format('exact pass: %d streams merged (%d ICC profiles)',
    [Exact.DuplicateStreams, Exact.ICCProfilesDeduplicated]));

  // 2. Perceptual: images that now share the same /ColorSpace and /SMask
  //    references can be compared on their pixels
  Lib.DeduplicateSimilarImages(2, 2, 6,
    PDF_RESOURCE_DEDUP_GARBAGE_COLLECT, Similar);
  Writeln(Format('perceptual pass: %d images merged, %d failed to decode',
    [Similar.ImagesDeduplicated, Similar.DecodeFailures]));
end;

Only indirect Image XObjects are scanned. Inline images written between BI and EI in a content stream have no object number to repoint and are left as they are. An image the decoder cannot read is skipped and counted in DecodeFailures: no pixel evidence, no merge

Eight band lookups instead of a quadratic scan

Comparing every image against every other image is quadratic, and a scanned archive with thousands of pages turns that into millions of sample comparisons. DeduplicateSimilarImages avoids it by splitting each 64-bit hash into eight 8-bit bands and keeping an ordered index over them

The pigeonhole principle does the rest. If two hashes differ in at most seven bits, those seven flips can touch at most seven of the eight bands, so at least one band is identical in both. Looking a candidate up band by band therefore finds every image within the permitted distance without a pairwise scan, and that is exactly why MaxHashDistance stops at 7: at eight differing bits the guarantee is gone

PDF Library for Delphi: The 64-bit difference hash splits into eight 8-bit bands, and the pigeonhole principle guarantees one band still matches after seven bit flips
Seven flipped bits across eight bands must leave one band intact, which turns a quadratic scan into eight ordered lookups

The band keys also carry the semantic signature, so a lookup only ever returns images that already share the same dictionary. Candidates are processed in ascending object and generation number, and within each group of matches the lowest-numbered image becomes canonical. Run the same input twice and you get the same canonical choices, which matters when the output is diffed against a previous build or signed afterwards

One consequence is easy to miss. A new image is compared only against canonical images, never against images that were already merged into one. Say B is within your thresholds of A, and C is within your thresholds of B but not of A. B merges into A; C stays a canonical image of its own. Generational re-encodes therefore cannot drift step by step away from the original: every merged image is within your thresholds of the image it is now displayed as

Reading the statistics before trusting a run

The TPDFlibImageSimilarityDedupStats record is the only feedback a batch job gets, so read more of it than the merge count. ImagesScanned, ImagesDecoded and DecodeFailures tell you how much of the document was actually considered. HashCandidates and CandidateComparisons show how many band hits survived the hash distance check and reached the pixel comparison. MaxAcceptedHashDistance, MaxAcceptedMeanError and MaxAcceptedChannelError show how close the loosest accepted merge came to each threshold

Those three maxima are the numbers to watch. If you allowed a mean error of 3 and MaxAcceptedMeanError reports 2.94, at least one merge sat right on the edge; tighten that threshold by one, run the dry run again, and see how many merges disappear. If the count barely changes, the edge case was isolated. If it halves, your threshold is doing more judging than you thought

DuplicatePayloadBytes counts the encoded stream data of the duplicates and nothing else. Each removed image also takes its dictionary, its indirect object wrapper and its cross-reference entry with it, so once garbage collection removes the orphans the real saving comes out slightly larger than the figure reported

Out-of-range arguments need a guard of your own. A hash distance of 8, a mean error above 255, or any option bit other than the two allowed flags makes DeduplicateSimilarImages return 0 with every statistic zeroed, which reads exactly like a document with nothing to merge. Thresholds that come from a configuration file deserve a check before the call:

// Reader-side helper, not part of the library: rejects threshold values
// that DeduplicateSimilarImages would answer with 0 and empty statistics
procedure CheckDedupThresholds(Hash, Mean, Channel: Integer);
begin
  if (Hash < 0) or (Hash > 7) then
    raise EArgumentException.CreateFmt('hash distance %d outside 0..7', [Hash]);
  if (Mean < 0) or (Mean > 255) or (Channel < 0) or (Channel > 255) then
    raise EArgumentException.CreateFmt(
      'error thresholds %d/%d outside 0..255', [Mean, Channel]);
end;

  CheckDedupThresholds(Cfg.Hash, Cfg.Mean, Cfg.Channel);
  Lib.DeduplicateSimilarImages(Cfg.Hash, Cfg.Mean, Cfg.Channel,
    PDF_RESOURCE_DEDUP_DRY_RUN, Stats);
  if (Stats.ImagesScanned > 0) and (Stats.ImagesDecoded = 0) then
    Writeln('images found, but none reached the pixel comparison');

What a 64 by 64 sample cannot see

The sample is a point sample. Each of the 4,096 cells takes the single pixel at its center; the rest of the cell is never read. For logos and thumbnails that is plenty, because a re-encode changes pixels everywhere and the center pixels change with them

For page-sized scans the gaps get wide. Suppose a batch of A4 pages scanned at 300 dpi, 2480 by 3508 pixels each: the sample points sit about 39 pixels apart horizontally and about 55 pixels apart vertically. A changed word or an initialed box that falls between those points never reaches the comparison, even with all three thresholds at zero. Zero thresholds mean the samples are identical, which is a weaker statement than the images being identical

So our position is blunt. For images that carry data rather than decoration, such as charts, maps, signatures, stamps, medical imagery and scanned contract pages, skip the perceptual pass entirely and rely on exact deduplication, which merges only genuinely identical streams and makes no visual judgment at all. For repeated letterheads and logos in scanned batches, a hash distance of 2 to 3 with a mean error around 2 merges reliably, and a channel error in the single digits should still reject a stamped or annotated copy

Where it belongs in a size-reduction pipeline

Order the passes by risk. Exact resource deduplication goes first, since it is lossless, cheap, and as shown above it unlocks merges the perceptual pass could not otherwise make. Font subsetting comes next; it is also lossless and usually the largest single win on text-heavy documents, as covered in PDF file size optimization and font subsetting. Image recompression or downsampling follows only if the target medium allows it. Perceptual deduplication runs last, because it is the only step whose result depends on a judgment call

PDF Library for Delphi: Recommended pipeline order from lossless exact deduplication and font subsetting to conditional image recompression, perceptual deduplication, and verification
Each step adds risk, so lossless wins come first and the judgment-call merge runs last, followed by a render-and-compare check

Set thresholds per document class, not once for the whole system. A scanned-letter workflow and a technical report generator have different tolerances, and a single global value ends up either too timid for the first or too loose for the second. Keep the dry-run statistics from the first few files of each class in your job log; they are the evidence for whatever thresholds you settle on

Then verify. Render a sample of pages before and after and compare them, and check that the image count dropped by the number the statistics promised. The route for seeing what a document actually spends its bytes on is described in auditing PDF file size by category, and running that audit first tells you whether images are worth optimizing at all

Exact deduplication, perceptual image merging and the size audit all work on the same loaded document from Delphi, C++Builder and Free Pascal; licensing and the rest of the optimization API are on the PDF Library for Delphi product page