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

Added ImageFile close() #8702

Merged
merged 2 commits into from
Jan 20, 2025
Merged
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
21 changes: 3 additions & 18 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,24 +603,16 @@ def _new(self, im: core.ImagingCore) -> Image:
def __enter__(self):
return self

def _close_fp(self):
if getattr(self, "_fp", False):
if self._fp != self.fp:
self._fp.close()
self._fp = DeferredError(ValueError("Operation on closed image"))
if self.fp:
self.fp.close()

def __exit__(self, *args):
if hasattr(self, "fp"):
from . import ImageFile

if isinstance(self, ImageFile.ImageFile):
if getattr(self, "_exclusive_fp", False):
self._close_fp()
self.fp = None

def close(self) -> None:
"""
Closes the file pointer, if possible.

This operation will destroy the image core and release its memory.
The image data will be unusable afterward.

Expand All @@ -629,13 +621,6 @@ def close(self) -> None:
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
more information.
"""
if hasattr(self, "fp"):
try:
self._close_fp()
self.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)

if getattr(self, "map", None):
self.map: mmap.mmap | None = None

Expand Down
33 changes: 32 additions & 1 deletion src/PIL/ImageFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,21 @@
import abc
import io
import itertools
import logging
import os
import struct
import sys
from typing import IO, TYPE_CHECKING, Any, NamedTuple, cast

from . import ExifTags, Image
from ._deprecate import deprecate
from ._util import is_path
from ._util import DeferredError, is_path

if TYPE_CHECKING:
from ._typing import StrOrBytesPath

logger = logging.getLogger(__name__)

MAXBLOCK = 65536

SAFEBLOCK = 1024 * 1024
Expand Down Expand Up @@ -163,6 +166,34 @@ def __init__(
def _open(self) -> None:
pass

def _close_fp(self):
if getattr(self, "_fp", False):
if self._fp != self.fp:
self._fp.close()
self._fp = DeferredError(ValueError("Operation on closed image"))
if self.fp:
self.fp.close()

def close(self) -> None:
"""
Closes the file pointer, if possible.

This operation will destroy the image core and release its memory.
The image data will be unusable afterward.

This function is required to close images that have multiple frames or
have not had their file read and closed by the
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
more information.
"""
try:
self._close_fp()
self.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)

super().close()

def get_child_images(self) -> list[ImageFile]:
child_images = []
exif = self.getexif()
Expand Down
Loading