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.
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).
| Parameter | Type | Description |
fp | str | Path | file-like | A filename (string), pathlib.Path object, or an object implementing read(), seek(), tell(). |
mode | str | The mode. If given, this argument must be "r" (the only option). |
formats | list | None | If given, only these formats will be attempted. Accepts a sequence of format identifiers. |
im = Image.open("photo.jpg")
with open("photo.jpg", "rb") as f:
im = Image.open(f)
im.load()
import io
buf = io.BytesIO(image_bytes)
im = Image.open(buf)
im = Image.open("file.jpg", formats=["JPEG", "PNG"])
Image.new()
Creates a new image with the given mode and size.
| Parameter | Type | Description |
mode | str | The mode to use for the new image (e.g., "RGB", "RGBA", "L"). |
size | tuple[int,int] | Image size as a (width, height) tuple. |
color | int | tuple | str | Fill colour. Default: 0. Can be a named colour like "red", a tuple (255,0,0), or an integer for single-band modes. |
img = Image.new("RGB", (200, 200), "red")
canvas = Image.new("RGBA", (400, 300), (0, 0, 0, 0))
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.
| Parameter | Type | Description |
mode | str | Image mode. |
size | tuple | (width, height). |
data | bytes | Raw pixel data. |
decoder_name | str | Decoder to use. Default: "raw". |
*args | — | Arguments passed to the decoder. |
data = bytes([255,0,0,255,
0,255,0,255,
0,0,255,255,
255,255,0,255])
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.
import numpy as np
from PIL import Image
arr = np.zeros((100, 200, 3), dtype=np.uint8)
arr[:, :, 0] = np.linspace(0, 255, 200)
img = Image.fromarray(arr)
img.save("gradient.png")
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.
| Parameter | Type | Description |
mode | str | The requested mode. See Modes reference. |
matrix | tuple | Optional 4- or 12-tuple for RGB ↔ RGB or RGB ↔ CMYK conversion matrix. |
dither | Dither | Dithering method. NONE or FLOYDSTEINBERG |
palette | Palette | Palette to use for P conversions. WEB or ADAPTIVE. |
colors | int | Number 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.
| Parameter | Type | Description |
fp | str | Path | file-like | Path or file object to save to. |
format | str | None | Optional format override (e.g., "JPEG", "PNG"). |
**params | — | Format-specific parameters. See Image Format docs. |
Compositing
| Method | Description |
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. |
base = Image.open("background.png").convert("RGBA")
logo = Image.open("logo.png").convert("RGBA")
logo_w = base.width // 5
logo_h = int(logo.height * logo_w / logo.width)
logo = logo.resize((logo_w, logo_h), Image.Resampling.LANCZOS)
pos = (base.width - logo_w - 20, base.height - logo_h - 20)
base.paste(logo, pos, mask=logo)
base.save("watermarked.png")
Pixel Access
| Method | Description |
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
| Constant | Values |
Image.Resampling | NEAREST, BOX, BILINEAR, HAMMING, BICUBIC, LANCZOS |
Image.Transpose | FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM, ROTATE_90, ROTATE_180, ROTATE_270, TRANSPOSE, TRANSVERSE |
Image.Transform | AFFINE, EXTENT, PERSPECTIVE, QUAD, MESH |
Image.Dither | NONE, FLOYDSTEINBERG, ORDERED, RASTERIZE |
Image.Palette | WEB, ADAPTIVE |
Image.MAX_IMAGE_PIXELS | Default: 178_956_970. Set to None to disable decompression bomb protection. |