Skip to content

Confusing errors when saving zero-dimension images instead of clear validation #9389

Description

@aayushadhikari7

What did you do?

Attempted to save an image with zero width or zero height.

from PIL import Image

img = Image.new('RGB', (0, 50))  # zero-width image
img.save('test.gif')
img.save('test.png')

What did you expect to happen?

A clear validation error like:

ValueError: Cannot save image with zero width or height (got size: (0, 50))

What actually happened?

GIF save:

ValueError: max() iterable argument is empty

(from GifImagePlugin.py line 959 in _get_optimize)

PNG save:

SystemError: tile cannot extend outside image

(from ImageFile.py line 682 in _encode_tile)

Context

I encountered this when using ImageGrab.grab(bbox=...) with programmatically-determined coordinates. When window detection returned invalid bounds (e.g., bbox=(50, 50, 50, 100) resulting in width=0), the save operation failed with these confusing errors.

from PIL import ImageGrab

frame = ImageGrab.grab(bbox=(50, 50, 50, 100))  # bad coords → width=0
print(frame.size)  # (0, 50)
frame.save('output.gif')  # confusing error

Note on existing issues

  • Issue Image of size zero is not getting initialized #2259 intentionally allowed creating zero-dimension images (for mathematical operations like fold/reduce)
  • Resizing to zero dimensions gives a clear error: height and width must be > 0
  • But saving zero-dimension images was never given proper validation

Suggested fix

Add dimension validation at the start of Image.save():

if self.size[0] == 0 or self.size[1] == 0:
    raise ValueError(
        f"Cannot save image with zero width or height (got size: {self.size})"
    )

Environment

  • Pillow version: 12.1.0
  • Python version: 3.12.5
  • Platform: Windows 11

Activity

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions