Skip to content
Tutorials Center
My learning

Topics

Lesson 119 of 149 ยท Data and the Web

Image Processing with Pillow

Learn image processing in Python with Pillow. Create and open images, resize and crop, convert to grayscale, apply filters, draw shapes and text, and save in other formats.

Photos, logos, thumbnails, screenshots, charts: images are everywhere, and sooner or later a program needs to resize, crop, convert or annotate them. Pillow is the standard Python library for this. It reads and writes dozens of formats (PNG, JPEG, GIF, WebP, BMP and more) and gives you a simple Image object with methods for the common jobs.

In this lesson you will create and open images, inspect their size and mode, resize and crop, convert to grayscale, apply filters, draw shapes and text, and save in different formats. Pillow's pixel math pairs well with NumPy and Matplotlib when you want to analyze or plot image data, and the file handling builds on Reading and Writing Files.

Installing and importing

Install Pillow into a virtual environment:

TEXT
python -m pip install pillow

The package is named pillow, but the module you import is PIL (a leftover from the original library, which Pillow replaced):

Python
from PIL import Image, ImageDraw, ImageFilter, ImageOps

On this site the examples build their own images in memory, so they need no files. Everything you see works the same with an image opened from disk using Image.open("photo.jpg").

Creating and inspecting images

Image.new(mode, size, color) makes a blank image. The mode says how pixels are stored: "RGB" has three channels (red, green, blue, each 0-255), "RGBA" adds transparency, "L" is a single grayscale channel, and "1" is pure black and white. The size is a (width, height) tuple, measured in pixels from the top-left corner, where (0, 0) is the top-left pixel and y grows downward.

Python Create an image and inspect it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Colors can be written as names ("navy"), hex strings ("#ff8800") or tuples ((255, 136, 0)). getpixel and putpixel are fine for a handful of pixels but slow for whole images. For bulk work use the built-in operations below, or convert the image to a NumPy array.

Opening, saving and converting formats

With real files, opening and saving look like this (read-only here because the editor has no files of yours):

Python
from PIL import Image

with Image.open("photo.jpg") as img:
    print(img.format, img.size, img.mode)   # e.g. JPEG (4032, 3024) RGB
    img.save("photo.png")                   # format picked from the extension
    img.save("small.webp", quality=80)      # options depend on the format

save() chooses the format from the file extension. Image.open() is lazy: it reads only the header at first and loads the pixels when you first use them, so wrap it in a with block to close the file when you are done.

The same works with memory buffers from io.BytesIO, which is also how you handle images from the web or a database. The next example saves an image to bytes in two formats and reads it back, so you can compare how formats behave:

Python Save to memory and reopen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

PNG is lossless and keeps transparency, which suits logos and screenshots. JPEG is lossy and much smaller for photos, but it cannot store transparency. The error in the example shows the fix: convert with .convert("RGB") before saving as JPEG.

Resizing, cropping and rotating

Most image tasks are geometry. Pillow's workhorses are:

Method What it does
img.resize((w, h)) returns a new image of exactly that size (may distort)
img.thumbnail((w, h)) shrinks in place, keeping the aspect ratio, to fit inside the box
img.crop((left, top, right, bottom)) returns the rectangle; the box is (left, top, right, bottom), not width and height
img.rotate(angle, expand=True) rotates counter-clockwise; expand=True enlarges the canvas so nothing is cut off
img.transpose(Image.Transpose.FLIP_LEFT_RIGHT) mirrors the image (ROTATE_90 etc. also exist)
ImageOps.fit(img, size) crops and resizes to fill the size exactly, no distortion

Methods that return a new image leave the original untouched. thumbnail() is the exception because it modifies the image it is called on and returns None, so do not write img = img.thumbnail(...).

flowchart LR
    A["Original<br/>800 x 600"] --> B["thumbnail((200, 200))<br/>200 x 150"]
    A --> C["resize((200, 200))<br/>200 x 200, stretched"]
    A --> D["ImageOps.fit(A, (200, 200))<br/>200 x 200, cropped"]

Three ways to get a small version of an 800 x 600 image: keep the ratio, stretch, or crop to fill.

Python Resize, crop and rotate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When shrinking photos, Pillow's default resampling already gives good results. If you want to choose, pass resample=Image.Resampling.LANCZOS (sharp, best for downsizing) or Image.Resampling.NEAREST (blocky, ideal for pixel art).

Colors, grayscale and filters

convert() changes the mode: img.convert("L") gives grayscale, and ImageOps.invert() makes a negative. The ImageFilter module adds ready-made filters you apply with img.filter(...): BLUR, GaussianBlur(radius), SHARPEN, CONTOUR, EDGE_ENHANCE and others.

To see what a filter does without viewing the picture, build an image with a hard edge (left half black, right half white) and look at pixel values across the edge:

Python Grayscale, invert and blur

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Grayscale mode "L" holds one number per pixel, 0 for black to 255 for white. The blur turns the sharp jump into a smooth ramp: pixels near the edge get intermediate gray values, while pixels far from it stay pure black or white. Other helpful tools are ImageEnhance.Brightness, Contrast and Color (each takes a factor where 1.0 means "unchanged"), and ImageOps.autocontrast, equalize and grayscale.

Drawing shapes and text

ImageDraw.Draw(img) gives you a pen that draws straight onto the image: line, rectangle, ellipse, polygon, point and text. Coordinates are pixel positions, and shape boxes are (left, top, right, bottom).

Python Draw a simple badge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

draw.text() uses a small built-in font by default. For real typography, load a font file with ImageFont.truetype("path/to/font.ttf", size=24) and pass it as font=. You can measure text with draw.textbbox((0, 0), "Hi", font=font) to center or right-align it.

Batch processing a folder

Pillow shines in scripts that repeat one operation across many files. This one (run on your computer) makes 300-pixel-wide thumbnails of every JPEG in a folder, using pathlib:

Python
from pathlib import Path
from PIL import Image

source = Path("photos")
target = Path("thumbs")
target.mkdir(exist_ok=True)

for path in source.glob("*.jpg"):
    with Image.open(path) as img:
        img.thumbnail((300, 300))
        img.save(target / f"{path.stem}_thumb.jpg", quality=85, optimize=True)
        print("Wrote", path.stem, img.size)

Phone photos often carry an EXIF orientation tag instead of actually rotating the pixels, so they appear sideways after processing. Call ImageOps.exif_transpose(img) right after opening to apply it. Also remember that opening an untrusted image can use a lot of memory (a "decompression bomb"); Pillow warns when an image is suspiciously large, and you can cap it with Image.MAX_IMAGE_PIXELS.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do you import to use Pillow in code?

    The package is installed as pillow, but the module is still called PIL for historical reasons.
  2. 2. What does img.thumbnail((200, 200)) do?

    thumbnail() modifies the image in place, keeps the aspect ratio and returns None. resize() is the one that returns a new image of an exact size.
  3. 3. Which box does img.crop(...) expect?

    Crop takes the left, top, right and bottom pixel coordinates of the rectangle, not its width and height.
  4. 4. Why does saving an RGBA image as JPEG fail?

    JPEG cannot store an alpha channel. Call img.convert("RGB") before saving, or choose PNG or WebP to keep transparency.
  5. 5. What is mode "L" in Pillow?

    Mode L holds one 8-bit value per pixel, from 0 (black) to 255 (white).

Summary

  • Import from PIL (from PIL import Image); install the package as pillow.
  • Image.new, Image.open and img.save create, load and write images; size, mode and format describe them; pixels are addressed from the top-left corner.
  • resize and crop return new images; thumbnail shrinks in place and keeps the ratio; ImageOps.fit crops to fill an exact size.
  • convert("L") makes grayscale, ImageFilter applies blur and sharpen, and ImageDraw draws shapes and text.
  • Convert RGBA to RGB before saving JPEG, use io.BytesIO for in-memory images, and apply ImageOps.exif_transpose to phone photos.

Next: Testing with pytest.