Skip to content

Commit

Permalink
Work around Pillow 8.3.1 DPI changes
Browse files Browse the repository at this point in the history
Pillow decided against round-tripping DPI values.
python-pillow/Pillow#5476

Fixes #802
  • Loading branch information
jbarlow83 committed Jul 14, 2021
1 parent 773e284 commit 37923ff
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
23 changes: 21 additions & 2 deletions src/ocrmypdf/helpers.py
Expand Up @@ -25,19 +25,31 @@


class Resolution(namedtuple('Resolution', ('x', 'y'))):
"""The number of pixels per inch in each 2D direction."""
"""The number of pixels per inch in each 2D direction.
Resolution objects are considered "equal" for == purposes if they are
equal to a reasonable tolerance.
"""

__slots__ = ()

# rel_tol after converting from dpi to pixels per meter and saving
# as integer with rounding, as many file formats
CONVERSION_ERROR = 0.002

def round(self, ndigits: int):
return Resolution(round(self.x, ndigits), round(self.y, ndigits))

def to_int(self):
return Resolution(int(round(self.x)), int(round(self.y)))

@classmethod
def _isclose(cls, a, b):
return isclose(a, b, rel_tol=cls.CONVERSION_ERROR)

@property
def is_square(self) -> bool:
return isclose(self.x, self.y, rel_tol=1e-3)
return self._isclose(self.x, self.y)

@property
def is_finite(self) -> bool:
Expand All @@ -61,6 +73,13 @@ def __str__(self):
def __repr__(self): # pragma: no cover
return f"Resolution({self.x}x{self.y} dpi)"

def __eq__(self, other):
if isinstance(other, tuple) and len(other) == 2:
other = Resolution(*other)
if not isinstance(other, Resolution):
return NotImplemented
return self._isclose(self.x, other.x) and self._isclose(self.y, other.y)


class NeverRaise(Exception):
"""An exception that is never raised"""
Expand Down
2 changes: 1 addition & 1 deletion tests/test_ghostscript.py
Expand Up @@ -72,7 +72,7 @@ def test_rasterize_rotated(francais, outdir, caplog):

with Image.open(outdir / 'out.png') as im:
assert im.size == (target_size[1], target_size[0])
assert im.info['dpi'] == (forced_dpi[1], forced_dpi[0])
assert im.info['dpi'] == forced_dpi.flip_axis()


def test_gs_render_failure(resources, outpdf):
Expand Down

0 comments on commit 37923ff

Please sign in to comment.