Skip to content

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

Closed

Description

@ROTl24

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.

Activity

  1. radarhere commented on Sep 13, 2026

    @radarhere
    Member

    Thinking mathematically, if the dimension rounds to zero, I'm more inclined to let it be zero, rather than forcing it to be at least 1px.

    So with #9673, contain() would return a 10x0 image, and pad() would return a completely black 10x10 image.

    What do you think?

  2. ROTl24 commented on Sep 14, 2026

    @ROTl24
    Author

    Ah, I missed those PRs — sorry for the duplicate. I was aiming to avoid the exception, so #9673 works for me too.

  3. added
    Bug
    on Oct 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions