Skip to content

BUG: Decode image samples with 16 bits per component - #4435

Open
metsw24-max wants to merge 1 commit into
py-pdf:mainfrom
metsw24-max:image-16-bit-samples
Open

metsw24-max wants to merge 1 commit into
py-pdf:mainfrom
metsw24-max:image-16-bit-samples

Conversation

@metsw24-max

Copy link
Copy Markdown
Contributor

16-bit image samples are decoded as 8-bit

Problem: page.images returns wrong pixels for image XObjects with /BitsPerComponent 16 (PDF 1.5 and later; img2pdf writes them for 16-bit PNGs, Photoshop for 16-bit exports). _xobj_to_image hands the big-endian 16-bit samples to Pillow in an 8-bit mode, so the result is built from the interleaved high and low bytes of the first half of the data. Streams that also use /Predictor 2 are wrong a second time: the TIFF branch of FlateDecode.decode undoes the prediction byte by byte, which drops the carry from the low into the high byte, and the error accumulates along each row.

Fix: the TIFF predictor adds whole 16-bit samples when /BitsPerComponent is 16, and _xobj_to_image keeps the most significant byte of each sample for the raw-sample filters before the data reaches Pillow. DCT, JPX, CCITT and JBIG2 data is left alone, as are images with 8 bits or fewer. Pillow has no 16-bit mode for multi-band images, and pdf.js and MuPDF reduce to 8 bits the same way, so this seemed the least surprising behaviour.

Checked against MuPDF: img2pdf output for 16-bit grey and RGB PNGs, synthetic /Predictor 2 images, and the 16-bit Photoshop image in iss2925.pdf from the test cache (object 456 with its 16-bit /SMask) now decode byte-identically to MuPDF's pixmaps. Tests added in tests/test_filters.py and tests/test_images.py; they fail on main and pass with the change. Sub-byte depths with /Predictor 2 are not touched here.

@codecov

codecov Bot commented Nov 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.87%. Comparing base (1e3e7e3) to head (81c2b41).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #4435   +/-   ##
=======================================
  Coverage   98.87%   98.87%           
=======================================
  Files          59       59           
  Lines       12299    12307    +8     
  Branches     2342     2346    +4     
=======================================
+ Hits        12161    12169    +8     
  Misses         68       68           
  Partials       70       70           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Comment thread pypdf/filters.py
Comment on lines +231 to +240
# Samples are big-endian 16-bit values. Adding them byte by byte
# would drop the carry from the low byte into the high byte.
bpp = colors * 2
for i in range(0, len(str_data_mut) - 1, 2):
if i % row_length >= bpp:
value = (
int.from_bytes(str_data_mut[i:i + 2], "big")
+ int.from_bytes(str_data_mut[i - bpp:i - bpp + 2], "big")
) % 65536
str_data_mut[i:i + 2] = value.to_bytes(2, "big")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is correct, but slow. Have a look at #4312 :-)

Comment thread pypdf/filters.py
Comment on lines +233 to +240
bpp = colors * 2
for i in range(0, len(str_data_mut) - 1, 2):
if i % row_length >= bpp:
value = (
int.from_bytes(str_data_mut[i:i + 2], "big")
+ int.from_bytes(str_data_mut[i - bpp:i - bpp + 2], "big")
) % 65536
str_data_mut[i:i + 2] = value.to_bytes(2, "big")

@MartinThoma MartinThoma Nov 15, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer if this was moved to FlateDecode in a new static function _decode_tiff_prediction_16_bit next to _decode_png_prediction:

Suggested change
bpp = colors * 2
for i in range(0, len(str_data_mut) - 1, 2):
if i % row_length >= bpp:
value = (
int.from_bytes(str_data_mut[i:i + 2], "big")
+ int.from_bytes(str_data_mut[i - bpp:i - bpp + 2], "big")
) % 65536
str_data_mut[i:i + 2] = value.to_bytes(2, "big")
str_data = FlateDecode._decode_tiff_prediction_16_bit(str_data, columns, colors)

This makes tracebacks easier to read, doesn't cost much in performance, and follow-up PRs might also get easier to read :-)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants