From fb9537d8b716ee9875cb4f7bb1806ff0d6c8a967 Mon Sep 17 00:00:00 2001 From: Johannes Schauer Marin Rodrigues Date: Sat, 25 Nov 2023 07:58:17 +0100 Subject: [PATCH] src/img2pdf.py: allow PNG input without dpi units but non-square dpi aspect ratio Closes: #181 --- src/img2pdf.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/img2pdf.py b/src/img2pdf.py index f851d92..82643d8 100755 --- a/src/img2pdf.py +++ b/src/img2pdf.py @@ -1311,7 +1311,19 @@ def get_imgmetadata( else: imgwidthpx, imgheightpx = imgdata.size - ndpi = imgdata.info.get("dpi", (default_dpi, default_dpi)) + ndpi = imgdata.info.get("dpi") + if ndpi is None: + # the PNG plugin of PIL adds the undocumented "aspect" field instead of + # the "dpi" field if the PNG pHYs chunk unit is not set to meters + if imgformat == ImageFormat.PNG and imgdata.info.get("aspect") is not None: + aspect = imgdata.info["aspect"] + # make sure not to go below the default dpi + if aspect[0] > aspect[1]: + ndpi = (default_dpi * aspect[0] / aspect[1], default_dpi) + else: + ndpi = (default_dpi, default_dpi * aspect[1] / aspect[0]) + else: + ndpi = (default_dpi, default_dpi) # In python3, the returned dpi value for some tiff images will # not be an integer but a float. To make the behaviour of # img2pdf the same between python2 and python3, we convert that