Image Module#

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.

Examples#

Open, rotate, and display an image (using the default viewer)#

The following script loads an image, rotates it 45 degrees, and displays it using an external viewer (usually xv on Unix, and the Paint program on Windows).

from PIL import Image
with Image.open("hopper.jpg") as im:
    im.rotate(45).show()

Create thumbnails#

The following script creates nice thumbnails of all JPEG images in the current directory preserving aspect ratios with 128x128 max resolution.

from PIL import Image
import glob, os

size = 128, 128

for infile in glob.glob("*.jpg"):
    file, ext = os.path.splitext(infile)
    with Image.open(infile) as im:
        im.thumbnail(size)
        im.save(file + ".thumbnail", "JPEG")

Functions#

Image processing#

Constructing images#

Generating images#

Registering plugins#

Note

These functions are for use by plugin authors. They are called when a plugin is loaded as part of preinit() or init(). Application authors can ignore them.

The Image Class#

An instance of the Image class has the following methods. Unless otherwise stated, all methods return a new instance of the Image class, holding the resulting image.

The following example converts an RGB image (linearly calibrated according to ITU-R 709, using the D65 luminant) to the CIE XYZ color space:

rgb2xyz = (
    0.412453, 0.357580, 0.180423, 0,
    0.212671, 0.715160, 0.072169, 0,
    0.019334, 0.119193, 0.950227, 0)
out = im.convert("RGB", rgb2xyz)

This crops the input image with the provided coordinates:

from PIL import Image

with Image.open("hopper.jpg") as im:

    # The crop method from the Image module takes four coordinates as input.
    # The right can also be represented as (left+width)
    # and lower can be represented as (upper+height).
    (left, upper, right, lower) = (20, 20, 100, 100)

    # Here the image "im" is cropped and assigned to new variable im_crop
    im_crop = im.crop((left, upper, right, lower))

This blurs the input image using a filter from the ImageFilter module:

from PIL import Image, ImageFilter

with Image.open("hopper.jpg") as im:

    # Blur the input image using the filter ImageFilter.BLUR
    im_blurred = im.filter(filter=ImageFilter.BLUR)

This helps to get the bands of the input image:

from PIL import Image

with Image.open("hopper.jpg") as im:
    print(im.getbands())  # Returns ('R', 'G', 'B')

This helps to get the bounding box coordinates of the input image:

from PIL import Image

with Image.open("hopper.jpg") as im:
    print(im.getbbox())
    # Returns four coordinates in the format (left, upper, right, lower)

This resizes the given image from (width, height) to (width/2, height/2):

from PIL import Image

with Image.open("hopper.jpg") as im:

    # Provide the target width and height of the image
    (width, height) = (im.width // 2, im.height // 2)
    im_resized = im.resize((width, height))

This rotates the input image by theta degrees counter clockwise:

from PIL import Image

with Image.open("hopper.jpg") as im:

    # Rotate the image by 60 degrees counter clockwise
    theta = 60
    # Angle is in degrees counter clockwise
    im_rotated = im.rotate(angle=theta)

This flips the input image by using the Transpose.FLIP_LEFT_RIGHT method.

from PIL import Image

with Image.open("hopper.jpg") as im:

    # Flip the image from left to right
    im_flipped = im.transpose(method=Image.Transpose.FLIP_LEFT_RIGHT)
    # To flip the image from top to bottom,
    # use the method "Image.Transpose.FLIP_TOP_BOTTOM"

Image Attributes#

Instances of the Image class have the following attributes:

Image.filename: str#

The filename or path of the source file. Only images created with the factory function open have a filename attribute. If the input is a file like object, the filename attribute is set to an empty string.

Image.format: str | None#

The file format of the source file. For images created by the library itself (via a factory function, or by running a method on an existing image), this attribute is set to None.

Image.mode: str#

Image mode. This is a string specifying the pixel format used by the image. Typical values are “1”, “L”, “RGB”, or “CMYK.” See Modes for a full list.

Image.size: tuple[int]#

Image size, in pixels. The size is given as a 2-tuple (width, height).

Image.width: int#

Image width, in pixels.

Image.height: int#

Image height, in pixels.

Image.palette: PIL.ImagePalette.ImagePalette | None#

Colour palette table, if any. If mode is “P” or “PA”, this should be an instance of the ImagePalette class. Otherwise, it should be set to None.

Image.info: dict#

A dictionary holding data associated with the image. This dictionary is used by file handlers to pass on various non-image information read from the file. See documentation for the various file handlers for details.

Most methods ignore the dictionary when returning new images; since the keys are not standardized, it’s not possible for a method to know if the operation affects the dictionary. If you need the information later on, keep a reference to the info dictionary returned from the open method.

Unless noted elsewhere, this dictionary does not affect saving files.

Image.is_animated: bool#

True if this image has more than one frame, or False otherwise.

This attribute is only defined by image plugins that support animated images. Plugins may leave this attribute undefined if they don’t support loading animated images, even if the given format supports animated images.

Given that this attribute is not present for all images use getattr(image, "is_animated", False) to check if Pillow is aware of multiple frames in an image regardless of its format.

See also

n_frames, seek() and tell()

Image.n_frames: int#

The number of frames in this image.

This attribute is only defined by image plugins that support animated images. Plugins may leave this attribute undefined if they don’t support loading animated images, even if the given format supports animated images.

Given that this attribute is not present for all images use getattr(image, "n_frames", 1) to check the number of frames that Pillow is aware of in an image regardless of its format.

See also

is_animated, seek() and tell()

Classes#

Constants#

PIL.Image.NONE#
PIL.Image.MAX_IMAGE_PIXELS#

Set to 89,478,485, approximately 0.25GB for a 24-bit (3 bpp) image. See open() for more information about how this is used.

Transpose methods#

Used to specify the Image.transpose() method to use.

Transform methods#

Used to specify the Image.transform() method to use.

class PIL.Image.Transform#
AFFINE#

Affine transform

EXTENT#

Cut out a rectangular subregion

PERSPECTIVE#

Perspective transform

QUAD#

Map a quadrilateral to a rectangle

MESH#

Map a number of source quadrilaterals in one operation

Resampling filters#

See Filters for details.

Dither modes#

Used to specify the dithering method to use for the convert() and quantize() methods.

class PIL.Image.Dither#
NONE#

No dither

ORDERED#

Not implemented

RASTERIZE#

Not implemented

FLOYDSTEINBERG#

Floyd-Steinberg dither

Palettes#

Used to specify the palette to use for the convert() method.

Quantization methods#

Used to specify the quantization method to use for the quantize() method.

class PIL.Image.Quantize#
MEDIANCUT#

Median cut. Default method, except for RGBA images. This method does not support RGBA images.

MAXCOVERAGE#

Maximum coverage. This method does not support RGBA images.

FASTOCTREE#

Fast octree. Default method for RGBA images.

LIBIMAGEQUANT#

libimagequant

Check support using PIL.features.check_feature() with feature="libimagequant".