From 63f5abc78481ed5023149163c026fc9d486dc7ae Mon Sep 17 00:00:00 2001 From: lazerg Date: Fri, 20 Nov 2026 09:46:22 +0500 Subject: [PATCH 1/2] Raise ValueError when blending with nan alpha --- Tests/test_image.py | 7 +++++++ src/PIL/Image.py | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/Tests/test_image.py b/Tests/test_image.py index 5f1d97a8a2f..8807166fb77 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -2,6 +2,7 @@ import io import logging +import math import os import shutil import sys @@ -619,6 +620,12 @@ def test_blend_i16(self, mode: str) -> None: assert Image.blend(im1, im2, -2.0).getpixel((0, 0)) == 0 assert Image.blend(im1, im2, 6.0).getpixel((0, 0)) == 65535 + def test_blend_nan(self) -> None: + im1 = Image.new("L", (2, 2), 10) + im2 = Image.new("L", (2, 2), 20) + with pytest.raises(ValueError, match="invalid alpha"): + Image.blend(im1, im2, math.nan) + def test_check_size(self) -> None: # Checking that the _check_size function throws value errors when we want it to with pytest.raises(ValueError): diff --git a/src/PIL/Image.py b/src/PIL/Image.py index b28f85abda4..1227eb20273 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -3848,6 +3848,10 @@ def blend(im1: Image, im2: Image, alpha: float) -> Image: :returns: An :py:class:`~PIL.Image.Image` object. """ + if math.isnan(alpha): + msg = "invalid alpha" + raise ValueError(msg) + im1.load() im2.load() return im1._new(core.blend(im1.im, im2.im, alpha)) From b8d75e4913f225359384db754193f3570c80e695 Mon Sep 17 00:00:00 2001 From: lazerg Date: Fri, 20 Nov 2026 09:48:42 +0500 Subject: [PATCH 2/2] Also raise ValueError for inf alpha --- Tests/test_image.py | 7 ++++--- src/PIL/Image.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Tests/test_image.py b/Tests/test_image.py index 8807166fb77..5ae48b6d9ad 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -620,11 +620,12 @@ def test_blend_i16(self, mode: str) -> None: assert Image.blend(im1, im2, -2.0).getpixel((0, 0)) == 0 assert Image.blend(im1, im2, 6.0).getpixel((0, 0)) == 65535 - def test_blend_nan(self) -> None: + def test_blend_invalid_alpha(self) -> None: im1 = Image.new("L", (2, 2), 10) im2 = Image.new("L", (2, 2), 20) - with pytest.raises(ValueError, match="invalid alpha"): - Image.blend(im1, im2, math.nan) + for alpha in (math.inf, math.nan): + with pytest.raises(ValueError, match="invalid alpha"): + Image.blend(im1, im2, alpha) def test_check_size(self) -> None: # Checking that the _check_size function throws value errors when we want it to diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 1227eb20273..ca49d0f109a 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -3848,7 +3848,7 @@ def blend(im1: Image, im2: Image, alpha: float) -> Image: :returns: An :py:class:`~PIL.Image.Image` object. """ - if math.isnan(alpha): + if math.isinf(alpha) or math.isnan(alpha): msg = "invalid alpha" raise ValueError(msg)