ImageOps.contain and pad fail when a narrow image rounds to zero pixels

Open Beginner friendly
#9,997 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
76/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
python

Research direction

Start in ImageOps.py at ImageOps.contain(), where the rounded calculated dimension is passed to resize(); inspect how ImageOps.pad() delegates to contain(). Reproduce the narrow and transposed cases from the issue, then verify that contain() preserves a one-pixel dimension and pad() places the result in the requested canvas without the zero-size error.

Written by the indexing model from the issue text.

Description

Resizing a narrow image with ImageOps.contain() can round the shorter dimension to zero, even when both requested dimensions are positive. ImageOps.pad() hits the same error because it calls contain().

from PIL import Image, ImageOps

image = Image.new("RGB", (100, 1), "red")
ImageOps.contain(image, (10, 10))
# ValueError: height and width must be > 0

ImageOps.pad(image, (10, 10))
# ValueError: height and width must be > 0

I would expect contain() to return a 10×1 image, and pad() to return that image within a 10×10 canvas. The transposed input, 1×100, fails too. A 20×1 input also fails at the half-pixel rounding boundary.

In contain(), the calculated dimension is passed directly from round() to resize(). Keeping that calculated dimension at least one pixel avoids the error.

Reproduced on Windows with Python 3.13.15 and Pillow 12.3.0, and with ImageOps.py from main at 0a61c530aed1a2792c6a47674ac2b70753bfccbb loaded against the same installed Pillow core. No external image or network access is needed for the reproduction.

Dominant language
Python
Stars
13.8k
Forks
2.5k
Avg merge
2d 7h
Merged PRs (30d)
91

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python-pillow/Pillow

All issues in python-pillow/Pillow

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.