Skip to content

Commit 4ff18e0

Browse files
committed
Moved file pointer handling into ImageFile close
1 parent cf7dd2f commit 4ff18e0

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

src/PIL/Image.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -619,8 +619,6 @@ def __exit__(self, *args):
619619

620620
def close(self) -> None:
621621
"""
622-
Closes the file pointer, if possible.
623-
624622
This operation will destroy the image core and release its memory.
625623
The image data will be unusable afterward.
626624
@@ -629,13 +627,6 @@ def close(self) -> None:
629627
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
630628
more information.
631629
"""
632-
if hasattr(self, "fp"):
633-
try:
634-
self._close_fp()
635-
self.fp = None
636-
except Exception as msg:
637-
logger.debug("Error closing: %s", msg)
638-
639630
if getattr(self, "map", None):
640631
self.map: mmap.mmap | None = None
641632

src/PIL/ImageFile.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import abc
3232
import io
3333
import itertools
34+
import logging
3435
import os
3536
import struct
3637
import sys
@@ -43,6 +44,8 @@
4344
if TYPE_CHECKING:
4445
from ._typing import StrOrBytesPath
4546

47+
logger = logging.getLogger(__name__)
48+
4649
MAXBLOCK = 65536
4750

4851
SAFEBLOCK = 1024 * 1024
@@ -163,6 +166,26 @@ def __init__(
163166
def _open(self) -> None:
164167
pass
165168

169+
def close(self) -> None:
170+
"""
171+
Closes the file pointer, if possible.
172+
173+
This operation will destroy the image core and release its memory.
174+
The image data will be unusable afterward.
175+
176+
This function is required to close images that have multiple frames or
177+
have not had their file read and closed by the
178+
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
179+
more information.
180+
"""
181+
try:
182+
self._close_fp()
183+
self.fp = None
184+
except Exception as msg:
185+
logger.debug("Error closing: %s", msg)
186+
187+
super().close()
188+
166189
def get_child_images(self) -> list[ImageFile]:
167190
child_images = []
168191
exif = self.getexif()

0 commit comments

Comments
 (0)