Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Tests/test_file_tiff_metadata.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import io
import math
import struct
from pathlib import Path

Expand Down Expand Up @@ -280,6 +281,30 @@ def test_writing_other_types_to_undefined(
assert reloaded.tag_v2[33723] == b"1"


@pytest.mark.parametrize(
"value, expected",
(
(IFDRational(1, 0), TiffTags.RATIONAL),
(IFDRational(-1, 0), TiffTags.SIGNED_RATIONAL),
),
)
def test_tagtype_on_zero_denominator(
value: IFDRational, expected: int, tmp_path: Path
) -> None:
info = TiffImagePlugin.ImageFileDirectory_v2()

info[37380] = value
assert info.tagtype[37380] == expected

im = hopper()
out = tmp_path / "temp.tiff"
im.save(out, tiffinfo=info)

with Image.open(out) as reloaded:
assert isinstance(reloaded, TiffImagePlugin.TiffImageFile)
assert math.isnan(reloaded.tag_v2[37380])


def test_undefined_zero(tmp_path: Path) -> None:
# Check that the tag has not been changed since this test was created
tag = TiffTags.TAGS_V2[45059]
Expand Down
16 changes: 16 additions & 0 deletions Tests/test_tiff_ifdrational.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import math
from fractions import Fraction
from pathlib import Path

Expand Down Expand Up @@ -74,3 +75,18 @@ def test_ifd_rational_save(
with Image.open(out) as reloaded:
assert isinstance(reloaded, TiffImagePlugin.TiffImageFile)
assert float(IFDRational(301, 1)) == float(reloaded.tag_v2[282])


@pytest.mark.parametrize(
"numerator, denominator, expected_result",
[
(1, 1, 1.0),
(1, 0, float("nan")),
],
)
def test_float_cast(numerator, denominator, expected_result):
value = float(IFDRational(numerator, denominator))
if math.isnan(expected_result):
assert value
else:
assert value == expected_result
5 changes: 4 additions & 1 deletion src/PIL/TiffImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,9 @@ def limit_rational(self, max_denominator: int) -> tuple[IntegralLike, int]:
f = self._val.limit_denominator(max_denominator)
return f.numerator, f.denominator

def __float__(self):
return float(self._val)

def __repr__(self) -> str:
return str(float(self._val))

Expand Down Expand Up @@ -688,7 +691,7 @@ def _setitem(self, tag: int, value: Any, legacy_api: bool) -> None:
if all(isinstance(v, IFDRational) for v in values):
for v in values:
assert isinstance(v, IFDRational)
if v < 0:
if v < 0 or (math.isnan(v) and float(v.numerator) < 0):
self.tagtype[tag] = TiffTags.SIGNED_RATIONAL
break
else:
Expand Down
Loading