Skip to content

Raise ValueError for zero or negative sizes in ImageOps contain/cover/pad/fit - #9856

Draft
hdimer wants to merge 1 commit into
python-pillow:mainfrom
hdimer:imageops-validate-size
Draft

Raise ValueError for zero or negative sizes in ImageOps contain/cover/pad/fit#9856
hdimer wants to merge 1 commit into
python-pillow:mainfrom
hdimer:imageops-validate-size

Conversation

@hdimer

@hdimer hdimer commented Aug 7, 2026

Copy link
Copy Markdown

ImageOps.contain, cover, pad and fit handle invalid output sizes inconsistently. Because they compute size[0] / size[1] before Image.resize validates the size, a zero height raises ZeroDivisionError; cover skips validation entirely for a zero or negative width (returning a wrong-sized image); and contain returns a wrong-sized image for a negative height.

Before, on a 100x50 image:

size contain cover pad fit
(0, 10) ValueError (20, 10) ValueError ValueError
(10, 0) ZeroDivisionError ZeroDivisionError ZeroDivisionError ZeroDivisionError
(-1, 10) ValueError (20, 10) ValueError ValueError
(10, -1) (10, 5) ValueError ValueError ValueError

This adds an up-front size check to contain, cover and fit (pad delegates to contain) that raises the core's own ValueError: height and width must be > 0 for any dimension <= 0, so all four behave consistently.

Testing

Added a parametrized test over the four functions and the zero/negative sizes above; it asserts a ValueError rather than a crash or a silently wrong result. The full Tests/test_imageops.py suite passes (62 tests) and ruff is clean. A release note is included.


Used AI assistance on this; I reviewed and tested the change myself.

…/pad/fit

These functions compute size[0] / size[1] before Image.resize can validate
the size, so a zero height raised ZeroDivisionError. cover also skipped
validation for a zero or negative width, and contain returned a wrong-sized
image for a negative height. Validate the requested size up front and raise
the core's own "height and width must be > 0" ValueError, so all four behave
consistently.
@radarhere radarhere added the 🤖-assisted AI-assisted label Aug 7, 2026
@radarhere

Copy link
Copy Markdown
Member

This topic has had some recent activity in other PRs.

#9672 suggested resolving the contain() ValueError by returning images of at least 1px.
In response, I created #9673, suggesting successfully returning an image where one dimension is zero.

I may investigate expanding #9673 to address these other operations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🤖-assisted AI-assisted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants