From 0cbcb8fa124bf7c65373a98e526595da00d3580f Mon Sep 17 00:00:00 2001 From: Johannes Schauer Marin Rodrigues Date: Thu, 8 Jun 2023 08:54:37 +0200 Subject: [PATCH] avoid converting palette PNG with alpha to RGB (closes: #158) --- src/img2pdf.py | 25 +++++++++++++++---------- src/img2pdf_test.py | 5 +++-- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/img2pdf.py b/src/img2pdf.py index 0931637..35141d0 100755 --- a/src/img2pdf.py +++ b/src/img2pdf.py @@ -2101,7 +2101,16 @@ def read_images(rawdata, colorspace, first_frame_only=False, rot=None): ) ) else: - if ( + if color in [Colorspace.P, Colorspace.PA] and iccp is not None: + # PDF does not support palette images with icc profile + if color == Colorspace.P: + newcolor = Colorspace.RGB + newimg = newimg.convert(mode="RGB") + elif color == Colorspace.PA: + newcolor = Colorspace.RGBA + newimg = newimg.convert(mode="RGBA") + smaskidat = None + elif ( color == Colorspace.RGBA or color == Colorspace.LA or color == Colorspace.PA @@ -2115,6 +2124,11 @@ def read_images(rawdata, colorspace, first_frame_only=False, rot=None): newcolor = color l, a = newimg.split() newimg = l + elif color == Colorspace.PA or ( + color == Colorspace.P and "transparency" in newimg.info + ): + newcolor = color + a = newimg.convert(mode="RGBA").split()[-1] else: newcolor = Colorspace.RGBA r, g, b, a = newimg.convert(mode="RGBA").split() @@ -2125,15 +2139,6 @@ def read_images(rawdata, colorspace, first_frame_only=False, rot=None): "Image contains an alpha channel. Computing a separate " "soft mask (/SMask) image to store transparency in PDF." ) - elif color in [Colorspace.P, Colorspace.PA] and iccp is not None: - # PDF does not support palette images with icc profile - if color == Colorspace.P: - newcolor = Colorspace.RGB - newimg = newimg.convert(mode="RGB") - elif color == Colorspace.PA: - newcolor = Colorspace.RGBA - newimg = newimg.convert(mode="RGBA") - smaskidat = None else: newcolor = color smaskidat = None diff --git a/src/img2pdf_test.py b/src/img2pdf_test.py index 00e5176..5d46343 100755 --- a/src/img2pdf_test.py +++ b/src/img2pdf_test.py @@ -4276,9 +4276,10 @@ def gif_transparent_pdf(tmp_path_factory, gif_transparent_img, request): == b"q\n45.0000 0 0 45.0000 0.0000 0.0000 cm\n/Im0 Do\nQ" ) assert p.pages[0].Resources.XObject.Im0.BitsPerComponent == 8 - assert p.pages[0].Resources.XObject.Im0.ColorSpace == "/DeviceRGB" + assert p.pages[0].Resources.XObject.Im0.ColorSpace[0] == "/Indexed" + assert p.pages[0].Resources.XObject.Im0.ColorSpace[1] == "/DeviceRGB" assert p.pages[0].Resources.XObject.Im0.DecodeParms.BitsPerComponent == 8 - assert p.pages[0].Resources.XObject.Im0.DecodeParms.Colors == 3 + assert p.pages[0].Resources.XObject.Im0.DecodeParms.Colors == 1 assert p.pages[0].Resources.XObject.Im0.DecodeParms.Predictor == 15 assert p.pages[0].Resources.XObject.Im0.Filter == "/FlateDecode" assert p.pages[0].Resources.XObject.Im0.Height == 60