Skip to content

Fix 0-size edge case in ImageOps.contain#9672

Open
hecko-yes wants to merge 2 commits into
python-pillow:mainfrom
hecko-yes:patch-1
Open

Fix 0-size edge case in ImageOps.contain#9672
hecko-yes wants to merge 2 commits into
python-pillow:mainfrom
hecko-yes:patch-1

Conversation

@hecko-yes

@hecko-yes hecko-yes commented Jun 14, 2026

Copy link
Copy Markdown

Alternative to #9673

I ran into ValueError: height and width must be > 0 when trying to contain a very skinny image in a very small box. This fixes that.

@radarhere

Copy link
Copy Markdown
Member

An alternative way of fixing this problem would be to actually return an image with zero width (or height). We don't have to resize the existing image - if size is (0, 8), we could just return Image.new(image.mode, size). I'm slightly more inclined to this solution from a mathematical perspective. Do you have any thoughts?

Regardless though, just as an aside... the visual output of this is still unsatisfying, right? As in, I expect you have a large collection of images, and you're looking to display all of them in a smaller way within boxes, so that a user can view all of them at once. But there's no way that the final output with one dimension being 1px is actually something that the user can easily interpret.

@hecko-yes

Copy link
Copy Markdown
Author

In my case, I'm scaling it down to speed up subsequent color analysis, so looking pretty isn't a concern, but I understand this is not the most common usecase.

For user-facing applications, I believe e.g. Windows does just give you a 1px-wide image. Twitter puts a limit on the aspect ratio and switch to cropping if the image is beyond it, but I'm not sure if that's a good fit for a primitive such as this.

I'm not sure how well images with a dimension of 0 work in the rest of Pillow, but I assume there's a good reason why Image.resize refuses to produce them. :P

@radarhere

Copy link
Copy Markdown
Member

Zero size images are permitted, except for some early Pillow versions.

The error when resizing an image was added in #1714. I don't mind it as a error that communicates 'There's no way that you actually wanted this, you must have done something wrong'. If anyone could provide an argument as to why you would ever want to use resize() directly to create a zero size image, I'd be personally open to changing Pillow's behaviour.

I've created #9673 as an alternative, to allow ImageOps.contain() to create zero width or height images.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants