diff --git a/Tests/test_image.py b/Tests/test_image.py index 5f1d97a8a2f..5ae48b6d9ad 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,13 @@ 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_invalid_alpha(self) -> None: + im1 = Image.new("L", (2, 2), 10) + im2 = Image.new("L", (2, 2), 20) + 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 with pytest.raises(ValueError): diff --git a/src/PIL/Image.py b/src/PIL/Image.py index b28f85abda4..ca49d0f109a 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.isinf(alpha) or math.isnan(alpha): + msg = "invalid alpha" + raise ValueError(msg) + im1.load() im2.load() return im1._new(core.blend(im1.im, im2.im, alpha))