From 0599db52f84e8dcfe4fef9377879644c920b8341 Mon Sep 17 00:00:00 2001 From: harshitdeora Date: Mon, 9 Nov 2026 21:31:29 +0530 Subject: [PATCH 1/2] Preserve EXIF subdirectories in compressed TIFFs --- Tests/test_file_libtiff.py | 49 ++++++++++++++++++++++++++++++++++++ docs/releasenotes/13.1.0.rst | 7 ++++++ src/PIL/TiffImagePlugin.py | 37 ++++++++++++++++++++++++--- src/encode.c | 20 ++++++++++++++- src/libImaging/TiffDecode.c | 13 ++++++++++ src/libImaging/TiffDecode.h | 2 ++ 6 files changed, 124 insertions(+), 4 deletions(-) diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index 2d7c5bd38ba..dee901800f1 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, @@ -58,6 +59,54 @@ def _assert_noerr(self, tmp_path: Path, im: ImageFile.ImageFile) -> None: class TestFileLibTiff(LibTiffTestCase): + @pytest.mark.parametrize("compression", ("tiff_lzw", "tiff_adobe_deflate")) + @pytest.mark.parametrize("use_file", (False, True)) + @pytest.mark.parametrize("save_all", (False, True)) + def test_save_exif_subifd( + self, tmp_path: Path, compression: str, use_file: bool, save_all: bool + ) -> None: + exif = Image.Exif() + exif[ExifTags.Base.Make] = "Canon" + expected = { + ExifTags.Base.ISOSpeedRatings: 400, + ExifTags.Base.DateTimeOriginal: "2026:11:08 12:00:00", + } + exif.get_ifd(ExifTags.IFD.Exif).update(expected) + interop = {ExifTags.Interop.InteropIndex: "R98"} + exif.get_ifd(ExifTags.IFD.Exif)[ExifTags.IFD.Interop] = interop + gps = {ExifTags.GPS.GPSMapDatum: "WGS-84"} + exif.get_ifd(ExifTags.IFD.GPSInfo).update(gps) + jpeg = io.BytesIO() + Image.new("RGB", (8, 8), (10, 20, 30)).save(jpeg, format="JPEG", exif=exif) + destination = tmp_path / "exif.tiff" if use_file else io.BytesIO() + + with Image.open(jpeg) as source: + frames = [source] + if save_all: + frames.append(Image.new("RGB", (8, 8), (30, 20, 10))) + source.save( + destination, + format="TIFF", + compression=compression, + exif=source.getexif(), + save_all=save_all, + append_images=frames[1:], + ) + with Image.open(destination) as saved: + assert saved.n_frames == len(frames) + for index, frame in enumerate(frames): + saved.seek(index) + assert saved.info["compression"] == compression + saved_exif = saved.getexif() + assert saved_exif[ExifTags.Base.Make] == "Canon" + assert ( + expected.items() + <= saved_exif.get_ifd(ExifTags.IFD.Exif).items() + ) + assert saved_exif.get_ifd(ExifTags.IFD.Interop) == interop + assert saved_exif.get_ifd(ExifTags.IFD.GPSInfo) == gps + assert_image_equal(saved, frame) + def test_version(self) -> None: version = features.version_codec("libtiff") assert version is not None diff --git a/docs/releasenotes/13.1.0.rst b/docs/releasenotes/13.1.0.rst index 34a2cce3cb2..44241e5629a 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -50,6 +50,13 @@ TODO Other changes ============= +EXIF metadata in compressed TIFF images +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Saving a compressed TIFF with an EXIF subdirectory now preserves that +metadata. Previously, passing EXIF metadata from an image such as a JPEG +could cause the TIFF save to fail. + Writing to read-only images ^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index 69b83f8a839..0f340c7f001 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 @@ -1857,7 +1858,18 @@ 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) + value = info.get_ifd(key) + if ( + libtiff + and key == EXIFIFD + and ExifTags.IFD.Interop in value + and not isinstance(value[ExifTags.IFD.Interop], dict) + ): + value = { + **value, + ExifTags.IFD.Interop: info.get_ifd(ExifTags.IFD.Interop), + } + ifd[key] = value else: ifd[key] = info.get(key) try: @@ -2041,12 +2053,30 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: SUBIFD, ] + # LibTIFF writes ClassicTIFF in native byte order. + subifds = bytearray() + subifd_prefix = II if sys.byteorder == "little" else MM + appender = fp if isinstance(fp, AppendingTiffWriter) else None # bits per sample is a single short in the tiff directory, not a list. atts: dict[int, Any] = {BITSPERSAMPLE: bits[0]} # Merge the ones that we have with (optional) more bits from # the original file, e.g x,y resolution so that we can # save(load('')) == original file. for tag, value in itertools.chain(ifd.items(), supplied_tags.items()): + if tag in TiffTags.TAGS_V2_GROUPS and isinstance(value, dict): + if tag in atts: + continue + offset = 8 + len(subifds) + subifd = ImageFileDirectory_v2(prefix=subifd_prefix, group=tag) + for key, item in value.items(): + subifd[key] = item + # The appender rebases the main IFD's pointer. Offsets inside + # the subdirectory already refer to the final file. + page_offset = appender.offsetOfNewPage if appender else 0 + subifds.extend(subifd.tobytes(page_offset + offset)) + if appender: + appender._libtiff_subifd_tags.add(tag) + value = offset # Libtiff can only process certain core items without adding # them to the custom dictionary. # Custom items are supported for int, float, unicode, string and byte @@ -2089,7 +2119,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(subifds)) encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig) try: encoder.setimage(im.im) @@ -2174,6 +2204,7 @@ def setup(self) -> None: self.whereToWriteNewIFDOffset: int | None = None self.offsetOfNewPage = 0 + self._libtiff_subifd_tags: set[int] = set() self.IIMM = iimm = self.f.read(4) self._bigtiff = b"\x2b" in iimm @@ -2358,7 +2389,7 @@ def fixIFD(self) -> None: offset = self._read(fmt_size) + self.offsetOfNewPage self._rewriteLast(offset, fmt_size) - if tag in self.Tags: + if tag in self.Tags or tag in self._libtiff_subifd_tags: cur_pos = self.f.tell() logger.debug( diff --git a/src/encode.c b/src/encode.c index 0c08ba0c2f8..85f3904cb11 100644 --- a/src/encode.c +++ b/src/encode.c @@ -824,6 +824,8 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) { Py_ssize_t fp; PyObject *tags, *types; + const char *subifds = NULL; + Py_ssize_t subifds_size = 0; PyObject *key, *value; Py_ssize_t pos = 0; int key_int, status, is_core_tag, is_var_length, num_core_tags, i; @@ -839,7 +841,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, + &subifds, + &subifds_size )) { return NULL; } @@ -889,6 +900,13 @@ PyImaging_LibTiffEncoderNew(PyObject *self, PyObject *args) { encoder->cleanup = ImagingLibTiffEncodeCleanup; + if (subifds_size && + !ImagingLibTiffWriteSubIFDs(&encoder->state, subifds, subifds_size)) { + Py_DECREF(encoder); + PyErr_SetString(PyExc_OSError, "cannot write TIFF subdirectories"); + return NULL; + } + num_core_tags = sizeof(core_tags) / sizeof(int); long bits_per_sample = 1; for (pos = 0; pos < tags_size; pos++) { diff --git a/src/libImaging/TiffDecode.c b/src/libImaging/TiffDecode.c index 137ea0052e4..9404be0afda 100644 --- a/src/libImaging/TiffDecode.c +++ b/src/libImaging/TiffDecode.c @@ -736,6 +736,19 @@ ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp) { return 1; } +int +ImagingLibTiffWriteSubIFDs(ImagingCodecState state, const char *data, tmsize_t size) { + TIFFSTATE *clientstate = (TIFFSTATE *)state->context; + TIFF *tiff = clientstate->tiff; + thandle_t handle = TIFFClientdata(tiff); + // The serialized directories start immediately after the ClassicTIFF header. + toff_t offset = sizeof(TIFFHeaderClassic); + if (TIFFGetSeekProc(tiff)(handle, offset, SEEK_SET) != offset) { + return 0; + } + return TIFFGetWriteProc(tiff)(handle, (void *)data, size) == size; +} + int ImagingLibTiffMergeFieldInfo( ImagingCodecState state, TIFFDataType field_type, int key, int is_var_length diff --git a/src/libImaging/TiffDecode.h b/src/libImaging/TiffDecode.h index 2a8a1813b11..d5ffba1d2bb 100644 --- a/src/libImaging/TiffDecode.h +++ b/src/libImaging/TiffDecode.h @@ -34,6 +34,8 @@ extern int ImagingLibTiffInit(ImagingCodecState state, int fp, uint32_t offset); extern int ImagingLibTiffEncodeInit(ImagingCodecState state, char *filename, int fp); +extern int +ImagingLibTiffWriteSubIFDs(ImagingCodecState state, const char *data, tmsize_t size); extern void ImagingLibTiffEncodeCleanup(ImagingCodecState state); extern int From c8e626acb93dc8a07d5fd47c223a85081601996f Mon Sep 17 00:00:00 2001 From: harshitdeora Date: Thu, 12 Nov 2026 23:27:26 +0530 Subject: [PATCH 2/2] Fix TIFF EXIF subdirectory type annotations --- Tests/test_file_libtiff.py | 9 +++++---- src/PIL/TiffImagePlugin.py | 29 ++++++++++++++++------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index dee901800f1..e7988c4fa4a 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -6,7 +6,7 @@ import os import re import sys -from typing import NamedTuple +from typing import Any, NamedTuple import pytest @@ -67,21 +67,21 @@ def test_save_exif_subifd( ) -> None: exif = Image.Exif() exif[ExifTags.Base.Make] = "Canon" - expected = { + expected: dict[int, Any] = { ExifTags.Base.ISOSpeedRatings: 400, ExifTags.Base.DateTimeOriginal: "2026:11:08 12:00:00", } exif.get_ifd(ExifTags.IFD.Exif).update(expected) interop = {ExifTags.Interop.InteropIndex: "R98"} exif.get_ifd(ExifTags.IFD.Exif)[ExifTags.IFD.Interop] = interop - gps = {ExifTags.GPS.GPSMapDatum: "WGS-84"} + gps: dict[int, Any] = {ExifTags.GPS.GPSMapDatum: "WGS-84"} exif.get_ifd(ExifTags.IFD.GPSInfo).update(gps) jpeg = io.BytesIO() Image.new("RGB", (8, 8), (10, 20, 30)).save(jpeg, format="JPEG", exif=exif) destination = tmp_path / "exif.tiff" if use_file else io.BytesIO() with Image.open(jpeg) as source: - frames = [source] + frames: list[Image.Image] = [source] if save_all: frames.append(Image.new("RGB", (8, 8), (30, 20, 10))) source.save( @@ -93,6 +93,7 @@ def test_save_exif_subifd( append_images=frames[1:], ) with Image.open(destination) as saved: + assert isinstance(saved, TiffImagePlugin.TiffImageFile) assert saved.n_frames == len(frames) for index, frame in enumerate(frames): saved.seek(index) diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index ad71c0e29d2..8d69376a295 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -2059,7 +2059,7 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: ] # LibTIFF writes ClassicTIFF in native byte order. - subifds = bytearray() + subifd_payload = bytearray() subifd_prefix = II if sys.byteorder == "little" else MM appender = fp if isinstance(fp, AppendingTiffWriter) else None # bits per sample is a single short in the tiff directory, not a list. @@ -2068,20 +2068,21 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: # the original file, e.g x,y resolution so that we can # save(load('')) == original file. for tag, value in itertools.chain(ifd.items(), supplied_tags.items()): + libtiff_value: Any = value if tag in TiffTags.TAGS_V2_GROUPS and isinstance(value, dict): if tag in atts: continue - offset = 8 + len(subifds) + offset = 8 + len(subifd_payload) subifd = ImageFileDirectory_v2(prefix=subifd_prefix, group=tag) for key, item in value.items(): subifd[key] = item # The appender rebases the main IFD's pointer. Offsets inside # the subdirectory already refer to the final file. page_offset = appender.offsetOfNewPage if appender else 0 - subifds.extend(subifd.tobytes(page_offset + offset)) + subifd_payload.extend(subifd.tobytes(page_offset + offset)) if appender: appender._libtiff_subifd_tags.add(tag) - value = offset + libtiff_value = offset # Libtiff can only process certain core items without adding # them to the custom dictionary. # Custom items are supported for int, float, unicode, string and byte @@ -2091,20 +2092,22 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: types[tag] = TiffTags.LONG8 elif tag in ifd.tagtype: types[tag] = ifd.tagtype[tag] - elif isinstance(value, (int, float, str, bytes)) or ( - isinstance(value, tuple) - and all(isinstance(v, (int, float, IFDRational)) for v in value) + elif isinstance(libtiff_value, (int, float, str, bytes)) or ( + isinstance(libtiff_value, tuple) + and all( + isinstance(v, (int, float, IFDRational)) for v in libtiff_value + ) ): type = TiffTags.lookup(tag).type if type: types[tag] = type if tag not in atts and tag not in blocklist: - if isinstance(value, str): - atts[tag] = value.encode("ascii", "replace") + b"\0" - elif isinstance(value, IFDRational): - atts[tag] = float(value) + if isinstance(libtiff_value, str): + atts[tag] = libtiff_value.encode("ascii", "replace") + b"\0" + elif isinstance(libtiff_value, IFDRational): + atts[tag] = float(libtiff_value) else: - atts[tag] = value + atts[tag] = libtiff_value if SAMPLEFORMAT in atts and len(atts[SAMPLEFORMAT]) == 1: atts[SAMPLEFORMAT] = atts[SAMPLEFORMAT][0] @@ -2124,7 +2127,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, bytes(subifds)) + a = (rawmode, _fp, filename, tags, types, bytes(subifd_payload)) encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig) try: encoder.setimage(im.im)