How do you resize an image in Pillow (PIL) while preserving its aspect ratio? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you resize an image in Pillow (PIL) while preserving its aspect ratio?

message-square
0

Call img.thumbnail((max_width, max_height), Image.Resampling.LANCZOS) to shrink an image in-place so it fits cleanly inside a bounding box without distorting proportions, or use ImageOps.contain(img, (max_width, max_height), Image.Resampling.LANCZOS) when you want a new resized Image returned—and also support upscaling smaller images proportionally.

Basic Example

from PIL import Image, ImageOps

with Image.open("photo.jpg") as img:
    # 1. Recommended (for downscaling): `img.thumbnail()` mutates `img` in-place
    #    and preserves aspect ratio within the (800, 800) bounding box:
    thumb = img.copy()
    thumb.thumbnail((800, 800), Image.Resampling.LANCZOS)
    print(thumb.size)  # e.g., (800, 600) for a 4:3 landscape image
    thumb.save("photo_thumb.jpg", quality=90)

    # 2. Recommended (non-mutating, supports BOTH downscaling AND upscaling):
    contained = ImageOps.contain(img, (1200, 1200), method=Image.Resampling.LANCZOS)
    print(contained.size)
    contained.save("photo_contained.jpg", quality=90)

Key Details & Edge Cases

  • img.thumbnail() ONLY downscales—it never enlarges smaller images:
    • If your input image is 400 × 300 and you call img.thumbnail((800, 800)), img stays 400 × 300 untouched. Use ImageOps.contain(img, (800, 800)) (introduced in Pillow 9.0) when you want smaller images scaled up proportionally to touch the bounding box edges as well as larger images scaled down.
  • Fix EXIF phone camera orientation BEFORE resizing (ImageOps.exif_transpose):
    • Smartphone photos often store portrait orientation in EXIF metadata tags rather than pixel dimensions. Always call img = ImageOps.exif_transpose(img) right after Image.open(...) so width and height aren’t swapped during resizing.
  • Avoid deprecated Image.ANTIALIAS / Image.LANCZOS aliases (removed in Pillow 10.0):
    • Pillow 10.0 removed top-level Image.ANTIALIAS and Image.LANCZOS. Always pass Image.Resampling.LANCZOS (highest quality for photos), Image.Resampling.BICUBIC, or Image.Resampling.NEAREST (sharp pixel art).
  • Exact target width or height with auto-calculated opposite dimension:
    • When scaling to a fixed width (e.g., target_w = 600) regardless of height, compute height proportionally with round() and pass to img.resize():
      target_w = 600
      target_h = round(img.height * (target_w / img.width))
      resized = img.resize((target_w, target_h), Image.Resampling.LANCZOS)
      
  • Filling an exact fixed canvas without distortion (ImageOps.pad vs. ImageOps.fit):
    • If your output must have exact pixel dimensions (such as 512 × 512 for ML models or avatars) without stretching:
      • ImageOps.pad(img, (512, 512), color=(0, 0, 0)) fits the whole image inside the box and adds letterbox/pillarbox padding around empty margins.
      • ImageOps.fit(img, (512, 512)) scales and center-crops excess edges to fill the entire box with zero borders.

Comparison of Aspect-Ratio-Preserving Resize Methods in Pillow (PIL)

Method Mutates In-Place or Returns New Image? Downscales Larger Images? Upscales Smaller Images? Best Used When
img.thumbnail((max_w, max_h), Image.Resampling.LANCZOS) (Recommended) In-place (returns None) Yes No (leaves smaller images unchanged) Generating web thumbnails or limiting max resolution without blurry upscaling.
ImageOps.contain(img, (max_w, max_h), method=...) (Recommended) Returns new Image Yes Yes (scales up to fit bounding box) Functional pipelines needing a new Image scaled cleanly to fit within (max_w, max_h) in either direction.
img.resize((target_w, calc_h), Image.Resampling.LANCZOS) Returns new Image Yes Yes Scaling to one exact dimension (target_w or target_h) with a manually computed proportional counterpart.
ImageOps.pad(...) / ImageOps.fit(...) Returns new Image Yes Yes Producing an exact fixed (width, height) output via letterboxing (pad) or center-cropping (fit).