Skip to content

fix: resolve indexed color image color distortion in PDF output (#1499)#1500

Open
wang0331 wants to merge 2 commits intoLibrePDF:masterfrom
wang0331:master
Open

fix: resolve indexed color image color distortion in PDF output (#1499)#1500
wang0331 wants to merge 2 commits intoLibrePDF:masterfrom
wang0331:master

Conversation

@wang0331
Copy link
Contributor

Root Cause

The core issue was that the indexed color image processing logic failed to comply with PDF specification requirements for pixel data storage:

  1. Pixel data was filled from the least significant bit (LSB) of the byte instead of the most significant bit (MSB) as mandated by PDF, leading to incorrect palette index parsing and color distortion.
  2. Pixel data lacked byte alignment (row stride calculation) — incomplete bytes at the end of each row were not padded with zeros, causing row misalignment and image garbling.
  3. 4-bit pixel values were not properly shifted to their correct bit positions in the byte, resulting in truncated or misplaced index values.
  4. Unsigned palette index values were incorrectly cast to signed bytes, leading to negative index values and invalid palette lookups.

Solution

  1. Implemented strict PDF-compliant bit packing: Fill pixel data starting from the MSB (bit 7) of each byte and adjust bit offset dynamically based on pixel bit depth (1/2/4/8 bits).
  2. Calculated row stride ((width * bitsPerPixel + 7) / 8) to ensure each row of pixel data occupies an integer number of bytes, with zero-padding for incomplete bytes at row boundaries.
  3. Added dedicated bit-shifting logic for 4-bit pixels to ensure they occupy contiguous 4-bit positions in the byte (MSB to LSB).
  4. Normalized palette index values using & 0xFF to maintain unsigned range (0-255) and prevent negative values.
  5. Enforced row boundary alignment by padding empty bytes at the end of each row to match the calculated row stride, ensuring no cross-row pixel splitting.

Related Issue: #1499

Unit-Tests for the new Feature/Bugfix

Executed org.openpdf.text.ImageTest to ensure correct results

Compatibilities Issues

Your real name

account:wang0331
name:Xue-Ren Wang

Testing details

example code from @DRoppelt

@sonarqubecloud
Copy link

@wang0331
Copy link
Contributor Author

wang0331 commented Feb 27, 2026

Hi! @DRoppelt
This PR addresses the indexed color image rendering issue you reported in #1499. I've tested your example code and successfully reproduced the expected results with the fix. Could you please test the modified code with your test cases to verify if the issue is fully resolved?
Thanks a lot for your help and feedback!

Hi! @andreasrosdalw could you please review this pr? thanks a lot!
image

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.

1 participant