From fd299e36cec4c12a0f201dbbbc1014dfaca7005a Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 26 Apr 2021 20:27:34 +1000 Subject: [PATCH] Reset handle when seeking backwards as well --- Tests/test_file_libtiff.py | 11 +++++++++++ src/PIL/TiffImagePlugin.py | 8 +++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/Tests/test_file_libtiff.py b/Tests/test_file_libtiff.py index c0d09d6ce..5d3fe3742 100644 --- a/Tests/test_file_libtiff.py +++ b/Tests/test_file_libtiff.py @@ -578,6 +578,17 @@ class TestFileLibTiff(LibTiffTestCase): TiffImagePlugin.READ_LIBTIFF = False + def test_multipage_seek_backwards(self): + TiffImagePlugin.READ_LIBTIFF = True + with Image.open("Tests/images/multipage.tiff") as im: + im.seek(1) + im.load() + + im.seek(0) + assert im.convert("RGB").getpixel((0, 0)) == (0, 128, 0) + + TiffImagePlugin.READ_LIBTIFF = False + def test__next(self): TiffImagePlugin.READ_LIBTIFF = True with Image.open("Tests/images/hopper.tif") as im: diff --git a/src/PIL/TiffImagePlugin.py b/src/PIL/TiffImagePlugin.py index 9d821dcf9..7aa57f267 100644 --- a/src/PIL/TiffImagePlugin.py +++ b/src/PIL/TiffImagePlugin.py @@ -1052,6 +1052,11 @@ class TiffImageFile(ImageFile.ImageFile): def _seek(self, frame): self.fp = self.__fp + + # reset buffered io handle in case fp + # was passed to libtiff, invalidating the buffer + self.fp.tell() + while len(self._frame_pos) <= frame: if not self.__next: raise EOFError("no more images in TIFF file") @@ -1059,9 +1064,6 @@ class TiffImageFile(ImageFile.ImageFile): f"Seeking to frame {frame}, on frame {self.__frame}, " f"__next {self.__next}, location: {self.fp.tell()}" ) - # reset buffered io handle in case fp - # was passed to libtiff, invalidating the buffer - self.fp.tell() self.fp.seek(self.__next) self._frame_pos.append(self.__next) logger.debug("Loading tags, location: %s" % self.fp.tell())