Skip to content
Back to top
View this page

# `ImageFile` module

The `ImageFile` module provides support functions for the image open and save functions.

In addition, it provides a `Parser` class which can be used to decode an image piece by piece (e.g. while receiving it over a network connection). This class implements the same consumer interface as the standard sgmllib and xmllib modules.

## Example: Parse an image

    from PIL import ImageFile

    fp = open("hopper.ppm", "rb")

    p = ImageFile.Parser()

    while 1:
        s = fp.read(1024)
        if not s:
            break
        p.feed(s)

    im = p.close()

    im.save("copy.jpg")

## Classes

class PIL.ImageFile._Tile

  Bases: `NamedTuple`

  _Tile(codec_name, extents, offset, args)

  codec_name: str

    Alias for field number 0

  extents: tuple[int, int, int, int] | None

    Alias for field number 1

  offset: int

    Alias for field number 2

  args: tuple[Any, ...] | str | None

    Alias for field number 3

class PIL.ImageFile.Parser

  Incremental image parser. This class implements the standard feed/close consumer interface.

  close() → Image

    (Consumer) Close the stream.

    Returns:

      An image object.

    Raises:

      OSError – If the parser failed to parse the image file either because it cannot be identified or cannot be decoded.

  feed(data: bytes) → None

    (Consumer) Feed data to the parser.

    Parameters:

      data – A string buffer.

    Raises:

      OSError – If the parser failed to parse the image file.

  reset() → None

    (Consumer) Reset the parser. Note that you can only call this method immediately after you’ve created a parser; parser instances cannot be reused.

class PIL.ImageFile.PyCodec
  cleanup() → None

    Override to perform codec specific cleanup

    Returns:

      None

  init(args: tuple[Any, ...]) → None

    Override to perform codec specific initialization

    Parameters:

      args – Tuple of arg items from the tile entry

    Returns:

      None

  setfd(fd: IO[bytes]) → None

    Called from ImageFile to set the Python file-like object

    Parameters:

      fd – A Python file-like object

    Returns:

      None

  setimage(im: Image.core.ImagingCore, extents: tuple[int, int, int, int] | None = None) → None

    Called from ImageFile to set the core output image for the codec

    Parameters:

      - im – A core image object

      - extents – a 4 tuple of (x0, y0, x1, y1) defining the rectangle for this tile

    Returns:

      None

class PIL.ImageFile.PyDecoder

  Bases: `PyCodec`

  Python implementation of a format decoder. Override this class and add the decoding logic in the `decode()` method.

  See Writing Your Own File Codec in Python

  decode(buffer: bytes | bytearray | memoryview | SupportsArrayInterface) → tuple[int, int]

    Override to perform the decoding process.

    Parameters:

      buffer – A bytes object with the data to be decoded.

    Returns:

      A tuple of `(bytes consumed, errcode)`. If finished with decoding return -1 for the bytes consumed. Err codes are from `ImageFile.ERRORS`.

  set_as_raw(data: bytes | bytearray, rawmode: str | None = None, extra: tuple[Any, ...] = ()) → None

    Convenience method to set the internal image from a stream of raw data

    Parameters:

      - data – Bytes to be set

      - rawmode – The rawmode to be used for the decoder. If not specified, it will default to the mode of the image

      - extra – Extra arguments for the decoder.

    Returns:

      None

class PIL.ImageFile.PyEncoder

  Bases: `PyCodec`

  Python implementation of a format encoder. Override this class and add the decoding logic in the `encode()` method.

  See Writing Your Own File Codec in Python

  encode(bufsize: int) → tuple[int, int, bytes]

    Override to perform the encoding process.

    Parameters:

      bufsize – Buffer size.

    Returns:

      A tuple of `(bytes encoded, errcode, bytes)`. If finished with encoding return 1 for the error code. Err codes are from `ImageFile.ERRORS`.

  encode_to_file(fh: int, bufsize: int) → int
    Parameters:

      - fh – File handle.

      - bufsize – Buffer size.

    Returns:

      If finished successfully, return 0. Otherwise, return an error code. Err codes are from `ImageFile.ERRORS`.

  encode_to_pyfd() → tuple[int, int]

    If `pushes_fd` is `True`, then this method will be used, and `encode()` will only be called once.

    Returns:

      A tuple of `(bytes consumed, errcode)`. Err codes are from `ImageFile.ERRORS`.

class PIL.ImageFile.ImageFile

  Bases: `Image`

  Base class for image file format handlers.

  custom_mimetype: str | None
  tile: list[_Tile]

    A list of tile descriptors

  decoderconfig: tuple[Any, ...]
  fp: IO[bytes] | None
  close() → 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 `load()` method. See File handling in Pillow for more information.

  get_child_images() → list[ImageFile]
  get_format_mimetype() → str | None
  verify() → None

    Check file integrity

  load() → Image.core.PixelAccess | None

    Load image data based on tile list

  load_prepare() → None
  load_end() → None

class PIL.ImageFile.StubHandler

  Bases: `ABC`

class PIL.ImageFile.StubImageFile

  Bases: `ImageFile`

  Base class for stub image loaders.

  A stub loader is an image loader that can identify files of a certain format, but relies on external code to load the file.

  load() → Image.core.PixelAccess | None

    Load image data based on tile list

## Constants

PIL.ImageFile.LOAD_TRUNCATED_IMAGES = False

  Whether or not to load truncated image files. User code may change this.

PIL.ImageFile.MAXBLOCK = 65536

  By default, Pillow processes image data in blocks. This helps to prevent excessive use of resources. Codecs may disable this behaviour with `_pulls_fd` or `_pushes_fd`.

  When reading an image, this is the number of bytes to read at once.

  When writing an image, this is the number of bytes to write at once. If the image width times 4 is greater, then that will be used instead. Plugins may also set a greater number.

  User code may set this to another number.

PIL.ImageFile.ERRORS

  Dict of known error codes returned from `PyDecoder.decode()`, `PyEncoder.encode()` `PyEncoder.encode_to_pyfd()` and `PyEncoder.encode_to_file()`.