diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index 2d7c5bd38ba..e7988c4fa4a 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -6,11 +6,12 @@ import os import re import sys -from typing import NamedTuple +from typing import Any, NamedTuple import pytest from PIL import ( + ExifTags, Image, ImageFile, ImageFilter, @@ -58,6 +59,55 @@ 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: 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: 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: list[Image.Image] = [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 isinstance(saved, TiffImagePlugin.TiffImageFile) + 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 ac205efb91b..8d4d685362b 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -54,6 +54,13 @@ Two new image processing operations are available in ImageOps. 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. + Scaling empty text ^^^^^^^^^^^^^^^^^^ diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index 5a151d495b9..8d69376a295 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 @@ -1862,7 +1863,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: @@ -2046,12 +2058,31 @@ def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: SUBIFD, ] + # LibTIFF writes ClassicTIFF in native byte order. + 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. 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()): + libtiff_value: Any = value + if tag in TiffTags.TAGS_V2_GROUPS and isinstance(value, dict): + if tag in atts: + continue + 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 + subifd_payload.extend(subifd.tobytes(page_offset + offset)) + if appender: + appender._libtiff_subifd_tags.add(tag) + 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 @@ -2061,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] @@ -2094,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) + a = (rawmode, _fp, filename, tags, types, bytes(subifd_payload)) encoder = Image._getencoder(im.mode, "libtiff", a, encoderconfig) try: encoder.setimage(im.im) @@ -2179,6 +2212,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 @@ -2363,7 +2397,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 859594426b8..f3946e4989d 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 *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; @@ -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, + &subifds, + &subifds_size )) { return NULL; } @@ -890,6 +901,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