Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In Image.Image.seek(), clear core image if mode or size has changed #8450

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
29 changes: 29 additions & 0 deletions Tests/test_imagefile.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,3 +428,32 @@ def test_encode(self) -> None:
def test_zero_height(self) -> None:
with pytest.raises(UnidentifiedImageError):
Image.open("Tests/images/zero_height.j2k")

def test_load_prepare(self):
class TestImageFile(ImageFile.ImageFile):
def _open(self) -> None:
self._mode = "1"
self._size = (1, 1)
self._frame = 0

def seek(self, frame: int) -> None:
self._mode = "L"
self._size = (2, 2)
self._frame = frame
super().seek(frame)

def tell(self) -> int:
return self._frame

fp = BytesIO()
im = TestImageFile(fp)
im.load_prepare()
assert im._im is not None

im.seek(1)
assert im._im is None

im.load_prepare()
assert im._im is not None
assert im._im.mode == im.mode
assert im._im.size == im.size
8 changes: 7 additions & 1 deletion src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -2633,10 +2633,16 @@ def seek(self, frame: int) -> None:
"""

# overridden by file handlers
if frame != 0:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it make impossible to call super().seek() for plugins prior Pillow 11?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...yes, an external plugin would fail calling super().seek() if the user had Pillow < 11.

I could add a dedicated new method instead of using super().seek(), but any way you look at the idea of this PR, it is new functionality.

if frame != self.tell():
# The file handler likely did not override this method
msg = "no more images in file"
raise EOFError(msg)

if self._im is not None and (
self.im.size != self.size or self.im.mode != self.mode
):
self._im = None

def show(self, title: str | None = None) -> None:
"""
Displays this image. This method is mainly intended for debugging purposes.
Expand Down
Loading