Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise ValueError for negative values when loading P1-P3 PPM images #7882

Merged
merged 1 commit into from Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion Tests/test_file_ppm.py
Expand Up @@ -241,13 +241,23 @@ def test_plain_ppm_token_too_long(tmp_path: Path, data: bytes) -> None:
im.load()


def test_plain_ppm_value_negative(tmp_path: Path) -> None:
path = str(tmp_path / "temp.ppm")
with open(path, "wb") as f:
f.write(b"P3\n128 128\n255\n-1")

with Image.open(path) as im:
with pytest.raises(ValueError, match="Channel value is negative"):
im.load()


def test_plain_ppm_value_too_large(tmp_path: Path) -> None:
path = str(tmp_path / "temp.ppm")
with open(path, "wb") as f:
f.write(b"P3\n128 128\n255\n256")

with Image.open(path) as im:
with pytest.raises(ValueError):
with pytest.raises(ValueError, match="Channel value too large"):
im.load()


Expand Down
3 changes: 3 additions & 0 deletions src/PIL/PpmImagePlugin.py
Expand Up @@ -270,6 +270,9 @@ def _decode_blocks(self, maxval: int) -> bytearray:
msg = b"Token too long found in data: %s" % token[: max_len + 1]
raise ValueError(msg)
value = int(token)
if value < 0:
msg_str = f"Channel value is negative: {value}"
raise ValueError(msg_str)
if value > maxval:
msg_str = f"Channel value too large for this mode: {value}"
raise ValueError(msg_str)
Expand Down