From 2f51cf0af8101c75f59bdc4590602e15577a116e Mon Sep 17 00:00:00 2001 From: nehareddy Date: Wed, 18 Nov 2026 22:47:32 -0800 Subject: [PATCH 1/2] Preserve nested EXIF metadata when saving compressed TIFFs --- Tests/test_file_libtiff.py | 81 ++++++++++++++++++++++++++++++++++++ docs/releasenotes/13.1.0.rst | 7 ++++ src/PIL/TiffImagePlugin.py | 43 ++++++++++++++++--- src/encode.c | 26 +++++++++++- 4 files changed, 151 insertions(+), 6 deletions(-) diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index 8ec89965929..3e8c52d86a5 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -11,6 +11,7 @@ import pytest from PIL import ( + ExifTags, Image, ImageFile, ImageFilter, @@ -982,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: diff --git a/docs/releasenotes/13.1.0.rst b/docs/releasenotes/13.1.0.rst index 22759b2fc72..3eb33e16ba1 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -196,3 +196,10 @@ Memory leak when merging a single band with a mismatched mode requested mode, such as ``Image.merge("F", [l_image])``, raised :py:exc:`ValueError` but leaked the memory allocated for the output image. 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. diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index 157d67e4f4d..17e552af28d 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -56,6 +56,7 @@ import math import os import struct +import sys import warnings from collections.abc import Callable, MutableMapping from fractions import Fraction @@ -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, {}) != {} ) @@ -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: @@ -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. @@ -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 ( @@ -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) @@ -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): @@ -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( diff --git a/src/encode.c b/src/encode.c index 69d9087b433..04a796b0a3b 100644 --- a/src/encode.c +++ b/src/encode.c @@ -825,6 +825,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; @@ -840,7 +842,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; } @@ -890,6 +901,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++) { From de2600f3c08d9edbe5af9015c69100e345a78a15 Mon Sep 17 00:00:00 2001 From: Andrew Murray <3112309+radarhere@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:09:01 +1100 Subject: [PATCH 2/2] Correct underline --- docs/releasenotes/13.1.0.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/releasenotes/13.1.0.rst b/docs/releasenotes/13.1.0.rst index 3eb33e16ba1..256019689b2 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -198,7 +198,7 @@ requested mode, such as ``Image.merge("F", [l_image])``, raised 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