Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
80 changes: 80 additions & 0 deletions Tests/test_file_libtiff.py
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,86 @@ def test_exif_ifd(self) -> None:
assert isinstance(reloaded, TiffImagePlugin.TiffImageFile)
assert reloaded.tag_v2[34665] == 125456

@pytest.mark.parametrize("compression", ["tiff_lzw", "tiff_adobe_deflate", "jpeg"])
@pytest.mark.parametrize("on_disk", [False, True])
@pytest.mark.parametrize("source", ["object", "bytes", "jpeg"])
def test_save_compressed_exif_ifds(
self, tmp_path: Path, compression: str, on_disk: bool, source: str
) -> None:
exif = Image.Exif()
exif[ExifTags.Base.Make] = "Camera"
exif.get_ifd(ExifTags.IFD.Exif)[ExifTags.Base.ISOSpeedRatings] = 400
exif.get_ifd(ExifTags.IFD.Exif)[
ExifTags.Base.DateTimeOriginal
] = "2026:11:18 12:34:56"
exif.get_ifd(ExifTags.IFD.GPSInfo)[ExifTags.GPS.GPSLatitudeRef] = "N"
exif.get_ifd(ExifTags.IFD.GPSInfo)[ExifTags.GPS.GPSLatitude] = (12, 34, 56)
exif.get_ifd(ExifTags.IFD.Exif)[ExifTags.IFD.Interop] = {1: "R98"}
out = tmp_path / "exif.tif" if on_disk else io.BytesIO()
im = Image.new("RGB", (8, 8), "red")
metadata = exif.tobytes() if source == "bytes" else exif
if source == "jpeg":
jpeg = io.BytesIO()
im.save(jpeg, "JPEG", exif=exif)
im = Image.open(jpeg)
metadata = im.getexif()
im.save(
out,
"TIFF",
compression=compression,
exif=metadata,
)
with Image.open(out) as reloaded:
assert reloaded.size == im.size
assert reloaded.getexif()[ExifTags.Base.Make] == "Camera"
actual = reloaded.getexif().get_ifd(ExifTags.IFD.Exif).copy()
actual.pop(ExifTags.IFD.Interop)
expected = exif.get_ifd(ExifTags.IFD.Exif).copy()
expected.pop(ExifTags.IFD.Interop)
assert actual == expected
assert reloaded.getexif().get_ifd(ExifTags.IFD.Interop) == {1: "R98"}
assert reloaded.getexif().get_ifd(ExifTags.IFD.GPSInfo) == (
exif.get_ifd(ExifTags.IFD.GPSInfo)
)
if compression != "jpeg":
assert_image_equal(im, reloaded)

def test_save_compressed_exif_multipage(self) -> None:
frames = []
for iso in (100, 200):
im = Image.new("RGB", (8, 8), "red")
exif = Image.Exif()
exif.get_ifd(ExifTags.IFD.Exif)[ExifTags.Base.ISOSpeedRatings] = iso
exif.get_ifd(ExifTags.IFD.Exif)[
ExifTags.Base.DateTimeOriginal
] = "2026:11:18 12:34:56"
exif.get_ifd(ExifTags.IFD.Exif)[ExifTags.IFD.Interop] = {1: "R98"}
im.encoderinfo = {"exif": exif}
frames.append(im)
out = io.BytesIO()
frames[0].save(
out,
"TIFF",
compression="tiff_lzw",
save_all=True,
append_images=frames[1:],
)
with Image.open(out) as reloaded:
assert isinstance(reloaded, TiffImagePlugin.TiffImageFile)
assert reloaded.n_frames == 2
for frame, iso in enumerate((100, 200)):
reloaded.seek(frame)
exif = reloaded.getexif()
assert (
exif.get_ifd(ExifTags.IFD.Exif)[ExifTags.Base.ISOSpeedRatings]
== iso
)
assert exif.get_ifd(ExifTags.IFD.Exif)[
ExifTags.Base.DateTimeOriginal
] == ("2026:11:18 12:34:56")
assert exif.get_ifd(ExifTags.IFD.Interop) == {1: "R98"}
assert_image_equal(frames[frame], reloaded)

def test_crashing_metadata(
self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
Expand Down
7 changes: 7 additions & 0 deletions docs/releasenotes/13.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,10 @@ BLP2 DXT images with a width of 1 or 2
BLP2 images using DXT1, DXT3 or DXT5 compression with a width of 1 or 2 pixels were
decoded incorrectly, and used up to four times more memory than needed while loading.
This has been fixed.

Compressed TIFF EXIF metadata
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Nested EXIF and GPS directories are now preserved when saving TIFF images with
libtiff compression. Previously, passing these directories could raise
``RuntimeError: Error setting from dictionary`` or omit newly created metadata.
43 changes: 38 additions & 5 deletions src/PIL/TiffImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
import math
import os
import struct
import sys
import warnings
from collections.abc import Callable, MutableMapping
from fractions import Fraction
Expand Down Expand Up @@ -1849,7 +1850,7 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
exif = Image.Exif()
exif.load(info)
info = exif
elif isinstance(info, Image.Exif) and not libtiff:
if isinstance(info, Image.Exif):
subifds.extend(
key for key in TiffTags.TAGS_V2_GROUPS if info._ifds.get(key, {}) != {}
)
Expand All @@ -1862,7 +1863,15 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
if libtiff and key in {IMAGEWIDTH, IMAGELENGTH}:
continue
if isinstance(info, Image.Exif) and key in TiffTags.TAGS_V2_GROUPS:
ifd[key] = info.get_ifd(key)
nested_ifd = info.get_ifd(key)
if (
key == ExifTags.IFD.Exif
and ExifTags.IFD.Interop in nested_ifd
and not isinstance(nested_ifd[ExifTags.IFD.Interop], dict)
):
nested_ifd = nested_ifd.copy()
nested_ifd[ExifTags.IFD.Interop] = info.get_ifd(ExifTags.IFD.Interop)
ifd[key] = nested_ifd
else:
ifd[key] = info.get(key)
try:
Expand Down Expand Up @@ -2024,6 +2033,9 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:

# optional types for non core tags
types = {}
# libtiff writes native-endian classic TIFFs. Serialize nested metadata
# immediately after its eight-byte header, before any image strips.
ifd_data = bytearray()
# STRIPOFFSETS and STRIPBYTECOUNTS are added by the library
# based on the data in the strip.
# OSUBFILETYPE is deprecated.
Expand All @@ -2050,6 +2062,15 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
if tag not in TiffTags.LIBTIFF_CORE:
if tag in TiffTags.TAGS_V2_GROUPS:
types[tag] = TiffTags.LONG8
if isinstance(value, dict) and tag not in atts:
subifd = ImageFileDirectory_v2(
prefix=II if sys.byteorder == "little" else MM, group=tag
)
for key, item in value.items():
subifd[key] = item
offset = 8 + len(ifd_data)
ifd_data.extend(subifd.tobytes(offset))
value = offset
elif tag in ifd.tagtype:
types[tag] = ifd.tagtype[tag]
elif isinstance(value, (int, float, str, bytes)) or (
Expand Down Expand Up @@ -2085,7 +2106,7 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
# pseudo tag requires that the COMPRESS tag was already set.
tags = list(atts.items())
tags.sort()
a = (rawmode, _fp, filename, tags, types)
a = (rawmode, _fp, filename, tags, types, bytes(ifd_data))
encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig)
try:
encoder.setimage(im.im)
Expand Down Expand Up @@ -2344,7 +2365,12 @@ def close(self) -> None:
if self.close_fp:
self.f.close()

def fixIFD(self) -> None:
def fixIFD(self, seen: set[int] | None = None) -> None:
if seen is None:
seen = set()
if self.f.tell() in seen:
return
seen.add(self.f.tell())
num_tags = self._read(8 if self._bigtiff else 2)

for i in range(num_tags):
Expand All @@ -2360,7 +2386,14 @@ def fixIFD(self) -> None:
offset = self._read(fmt_size) + self.offsetOfNewPage
self._rewriteLast(offset, fmt_size)

if tag in self.Tags:
if tag in TiffTags.TAGS_V2_GROUPS and is_local and count == 1:
cur_pos = self.f.tell()
offset = self._read(fmt_size) + self.offsetOfNewPage
self._rewriteLast(offset, fmt_size)
self.f.seek(offset)
self.fixIFD(seen)
self.f.seek(cur_pos + fmt_size)
elif tag in self.Tags:
cur_pos = self.f.tell()

logger.debug(
Expand Down
26 changes: 25 additions & 1 deletion src/encode.c
Original file line number Diff line number Diff line change
Expand Up @@ -840,6 +840,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
Py_ssize_t fp;

PyObject *tags, *types;
const char *ifd_data = NULL;
Py_ssize_t ifd_size = 0;
PyObject *key, *value;
Py_ssize_t pos = 0;
int key_int, status, is_core_tag, is_var_length, num_core_tags, i;
Expand All @@ -855,7 +857,16 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {
PyObject *item;

if (!PyArg_ParseTuple(
args, "ssnsOO", &mode_name, &rawmode_name, &fp, &filename, &tags, &types
args,
"ssnsOO|y#",
&mode_name,
&rawmode_name,
&fp,
&filename,
&tags,
&types,
&ifd_data,
&ifd_size
)) {
return NULL;
}
Expand Down Expand Up @@ -905,6 +916,19 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) {

encoder->cleanup = ImagingLibTiffEncodeCleanup;

if (ifd_size) {
TIFF *tiff = ((TIFFSTATE *)encoder->state.context)->tiff;
thandle_t handle = TIFFClientdata(tiff);
// Python serialized these directories with offsets relative to the
// native-endian classic TIFF header emitted by EncodeInit.
if (TIFFGetSeekProc(tiff)(handle, 8, SEEK_SET) != 8 ||
TIFFGetWriteProc(tiff)(handle, (void *)ifd_data, ifd_size) != ifd_size) {
Py_DECREF(encoder);
PyErr_SetString(PyExc_OSError, "Error writing TIFF metadata");
return NULL;
}
}

num_core_tags = sizeof(core_tags) / sizeof(int);
long bits_per_sample = 1;
for (pos = 0; pos < tags_size; pos++) {
Expand Down
Loading