Documentation Menu

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.

Import
from PIL import Image

Image.open()

Open and identify the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).

ParameterTypeDescription
fpstr | Path | file-likeA filename (string), pathlib.Path object, or an object implementing read(), seek(), tell().
modestrThe mode. If given, this argument must be "r" (the only option).
formatslist | NoneIf given, only these formats will be attempted. Accepts a sequence of format identifiers.
Image.open() Examples
# Open from file path im = Image.open("photo.jpg") # Open from file object with open("photo.jpg", "rb") as f: im = Image.open(f) im.load() # Must load before closing file # Open from BytesIO buffer import io buf = io.BytesIO(image_bytes) im = Image.open(buf) # Limit to specific formats im = Image.open("file.jpg", formats=["JPEG", "PNG"])

Image.new()

Creates a new image with the given mode and size.

ParameterTypeDescription
modestrThe mode to use for the new image (e.g., "RGB", "RGBA", "L").
sizetuple[int,int]Image size as a (width, height) tuple.
colorint | tuple | strFill colour. Default: 0. Can be a named colour like "red", a tuple (255,0,0), or an integer for single-band modes.
Image.new() Examples
# Create a 200x200 solid red RGB image img = Image.new("RGB", (200, 200), "red") # Create a transparent 400x300 RGBA canvas canvas = Image.new("RGBA", (400, 300), (0, 0, 0, 0)) # Create a black 100x100 grayscale image gray = Image.new("L", (100, 100), 0)

Image.frombytes()

Creates a copy of an image memory from pixel data in a buffer. Useful when working with raw image data from camera SDKs, hardware devices, or other sources.

ParameterTypeDescription
modestrImage mode.
sizetuple(width, height).
databytesRaw pixel data.
decoder_namestrDecoder to use. Default: "raw".
*argsArguments passed to the decoder.
frombytes Example
# Create from raw bytes (RGBA, 2x2 image) data = bytes([255,0,0,255, # red 0,255,0,255, # green 0,0,255,255, # blue 255,255,0,255]) # yellow img = Image.frombytes("RGBA", (2, 2), data)

Image.fromarray()

Creates an image from a numpy array. This is the primary bridge between Pillow and the scientific Python ecosystem.

fromarray Example
import numpy as np from PIL import Image # Create a gradient array arr = np.zeros((100, 200, 3), dtype=np.uint8) arr[:, :, 0] = np.linspace(0, 255, 200) # Red gradient img = Image.fromarray(arr) # Mode auto-detected as "RGB" img.save("gradient.png")

Instance Methods

convert()

Returns a converted copy of this image. For the "P" mode, this method translates pixels through the palette. If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette.

ParameterTypeDescription
modestrThe requested mode. See Modes reference.
matrixtupleOptional 4- or 12-tuple for RGB ↔ RGB or RGB ↔ CMYK conversion matrix.
ditherDitherDithering method. NONE or FLOYDSTEINBERG
palettePalettePalette to use for P conversions. WEB or ADAPTIVE.
colorsintNumber of colors for ADAPTIVE palette. Default: 256.

save()

Saves this image in the given format. If no format is specified, the format to use is determined from the filename extension, if possible. Keyword arguments are passed to format-specific save handlers.

ParameterTypeDescription
fpstr | Path | file-likePath or file object to save to.
formatstr | NoneOptional format override (e.g., "JPEG", "PNG").
**paramsFormat-specific parameters. See Image Format docs.

Transforms

MethodSignatureReturns
resize()resize(size, resample=BICUBIC, box=None, reducing_gap=None)Image
thumbnail()thumbnail(size, resample=BICUBIC, reducing_gap=2.0)None (in-place)
crop()crop(box=None)Image
rotate()rotate(angle, resample=NEAREST, expand=False, center=None, translate=None, fillcolor=None)Image
transpose()transpose(method)Image
transform()transform(size, method, data=None, resample=NEAREST, fill=1, fillcolor=None)Image
reduce()reduce(factor, box=None)Image

Compositing

MethodDescription
im.paste(im2, box=None, mask=None)Paste im2 into image at box. If mask is given, update only the region indicated by the mask.
im.alpha_composite(im2, dest=(0,0), source=(0,0))Composite im2 over this image in-place. Both must be RGBA.
Image.alpha_composite(im1, im2)Static version. Returns new composited image.
Image.blend(im1, im2, alpha)Return new image as: im1 * (1 - alpha) + im2 * alpha.
Image.composite(image1, image2, mask)Create composite using mask. Same as paste() but returns new image.
Compositing Example
base = Image.open("background.png").convert("RGBA") logo = Image.open("logo.png").convert("RGBA") # Resize logo to 20% of base width logo_w = base.width // 5 logo_h = int(logo.height * logo_w / logo.width) logo = logo.resize((logo_w, logo_h), Image.Resampling.LANCZOS) # Position: bottom-right corner with 20px margin pos = (base.width - logo_w - 20, base.height - logo_h - 20) base.paste(logo, pos, mask=logo) base.save("watermarked.png")

Pixel Access

MethodDescription
im.load()Allocates storage and returns a PixelAccess object for fast pixel read/write. Preferred for bulk operations.
im.getpixel(xy)Returns the pixel value at the given position. For RGB images, returns a tuple (R, G, B).
im.putpixel(xy, value)Sets pixel value at position. Very slow in a loop — use load() instead.
im.histogram()Returns a list of pixel counts per level. Length = 256 for L mode, 768 for RGB.
im.getcolors(maxcolors=256)Returns a list of (count, color) tuples. Returns None if there are more colors than maxcolors.

Constants & Enums

ConstantValues
Image.ResamplingNEAREST, BOX, BILINEAR, HAMMING, BICUBIC, LANCZOS
Image.TransposeFLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM, ROTATE_90, ROTATE_180, ROTATE_270, TRANSPOSE, TRANSVERSE
Image.TransformAFFINE, EXTENT, PERSPECTIVE, QUAD, MESH
Image.DitherNONE, FLOYDSTEINBERG, ORDERED, RASTERIZE
Image.PaletteWEB, ADAPTIVE
Image.MAX_IMAGE_PIXELSDefault: 178_956_970. Set to None to disable decompression bomb protection.