Skip to content

Raise ValueError for invalid PNG text keys - #10322

Merged
radarhere merged 3 commits into
python-pillow:mainfrom
wleeaf:png-text-key-check
Oct 28, 2026
Merged

radarhere merged 3 commits into
python-pillow:mainfrom
wleeaf:png-text-key-check

Conversation

@wleeaf

@wleeaf wleeaf commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

PngInfo.add_text() and PngInfo.add_itxt() write whatever key they are given. The PNG specification requires text keys to be 1 to 79 characters long, and a key ends at the first null character, so some keys can't be read back. I saved a 1x1 image with each key and value "value", then read it with Pillow and with libpng 1.6.43 (png_get_text):

  • Empty key: Pillow ignores the tEXt and zTXt chunks, and libpng ignores the zTXt and iTXt chunks ("bad keyword").
  • 80-character key: libpng ignores the zTXt and iTXt chunks.
  • Key "a\0b":
    • The tEXt chunk is read back as {"a": "b\x00value"}.
    • Pillow and libpng both ignore the iTXt chunk.
    • With a zTXt chunk, Pillow can't open the saved image (UnidentifiedImageError), because it reads the rest of the key as the compression method.

pngcheck reports all of these files as errors.

Changes proposed in this pull request:

  • add_text() and add_itxt() raise a ValueError for a key that is empty, longer than 79 characters or contains a null character. They raise it before anything is added to the PngInfo. Keys of up to 79 characters still work.
  • Tests: test_invalid_text_key checks those keys as str and bytes, for tEXt, zTXt and iTXt, through both methods. test_text_key_max_length round-trips 79-character keys.
  • A release note under API changes.

The specification also forbids control characters and leading, trailing or consecutive spaces in keys. Pillow and libpng read those keys back unchanged, though, so I left them alone rather than break existing code that uses them.

The full test suite passes. ruff, black, mypy and sphinx-lint are clean on the changed files.

@radarhere radarhere added the 🤖-assisted AI-assisted label Oct 27, 2026
@radarhere
radarhere enabled auto-merge (squash) October 28, 2026 01:33
@radarhere
radarhere merged commit 75d6d6d into python-pillow:main Oct 28, 2026
50 checks passed
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