From 204c9d6ae19851c182e31da34e41f1bcd75ea6b3 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Wed, 7 Oct 2020 04:08:50 -0700 Subject: [PATCH] Fix inverted colors during JBIG2 optimization on paletted images Fixes #640 --- docs/release_notes.rst | 6 ++++++ src/ocrmypdf/optimize.py | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/docs/release_notes.rst b/docs/release_notes.rst index 55d9bb30..c697aaf4 100644 --- a/docs/release_notes.rst +++ b/docs/release_notes.rst @@ -12,6 +12,12 @@ may be unreliable. Use the API to depend on precise behavior. The public API may be useful in scripts that launch OCRmyPDF processes or that wish to use some of its features for working with PDFs. +v11.2.1 +======= + +- Fixed an issue where optimization of a 1-bit image with a color palette or + associated ICC that was optimized to JBIG2 could have its colors inverted. + v11.2.0 ======= diff --git a/src/ocrmypdf/optimize.py b/src/ocrmypdf/optimize.py index 9677879b..a9adba77 100644 --- a/src/ocrmypdf/optimize.py +++ b/src/ocrmypdf/optimize.py @@ -116,12 +116,23 @@ def extract_image_jbig2( and jbig2enc.available() ): try: + # Save any colorspace associated with the image, so that we + # will export a pure 1-bit PNG with no palette or ICC profile. + # Showing the palette or ICC to jbig2enc will cause it to perform + # colorspace transform to 1bpp, which will conflict the palette or + # ICC if it exists. + colorspace = pim.obj.ColorSpace + # Set to DeviceGray temporarily; we already in 1 bpc. + pim.obj.ColorSpace = pikepdf.Name.DeviceGray imgname = root / f'{xref:08d}' with imgname.open('wb') as f: ext = pim.extract_to(stream=f) imgname.rename(imgname.with_suffix(ext)) except pikepdf.UnsupportedImageTypeError: return None + finally: + # Restore image colorspace after temporarily setting it to DeviceGray + pim.obj.ColorSpace = colorspace return XrefExt(xref, ext) return None