Opening, shrinking and saving images with Pillow

BeginnerImage processingImage processing

Goal: Preparing dataset images at a uniform size.

Python — example.py
from PIL import Image, ImageOps

img = Image.new("RGB", (640, 480), (30, 120, 200))
img.save("sample.jpg", quality=90)
im = Image.open("sample.jpg")
print("Original size:", im.size, im.mode)
im.thumbnail((224, 224))
print("After thumbnail:", im.size)
sq = ImageOps.fit(Image.open("sample.jpg"), (224, 224))
print("After square crop:", sq.size, "| grey:", sq.convert("L").mode)

Code explanation

We create an image, save it and reopen it, use thumbnail to shrink it while keeping the aspect ratio, and convert to change colour modes.

Requirements

Shell
pip install pillow

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Original size: (640, 480) RGB
After thumbnail: (224, 168)
After square crop: (224, 224) | grey: L

This example was actually run and tested on 21 November 2026 on a CPU — pillow 13.0.0, python 3.13.18

Libraries used

Related examples