diff --git a/Tests/test_imageops.py b/Tests/test_imageops.py index a1dc65e6f11..f2519a284cf 100644 --- a/Tests/test_imageops.py +++ b/Tests/test_imageops.py @@ -423,6 +423,33 @@ def test_colorize_3color_offset() -> None: ) +def test_colorize_invalid_mode() -> None: + with pytest.raises(ValueError, match="mode must be L, not RGB"): + ImageOps.colorize(hopper("RGB"), "black", "white") + + +@pytest.mark.parametrize("blackpoint, whitepoint", ((-1, 255), (0, 256), (200, 50))) +def test_colorize_invalid_points(blackpoint: int, whitepoint: int) -> None: + with pytest.raises(ValueError, match="blackpoint and whitepoint must each be"): + ImageOps.colorize( + hopper("L"), "black", "white", blackpoint=blackpoint, whitepoint=whitepoint + ) + + +@pytest.mark.parametrize("midpoint", (100, 200)) +def test_colorize_invalid_midpoint(midpoint: int) -> None: + with pytest.raises(ValueError, match="midpoint must be between or equal to"): + ImageOps.colorize( + hopper("L"), + "black", + "white", + mid="blue", + blackpoint=125, + midpoint=midpoint, + whitepoint=175, + ) + + def test_exif_transpose() -> None: exts = [".jpg"] if features.check("webp"): diff --git a/src/PIL/ImageOps.py b/src/PIL/ImageOps.py index b98bd79b816..cdec4d5dc7d 100644 --- a/src/PIL/ImageOps.py +++ b/src/PIL/ImageOps.py @@ -200,12 +200,18 @@ def colorize( :return: An image. """ - # Initial asserts - assert image.mode == "L" - if mid is None: - assert 0 <= blackpoint <= whitepoint <= 255 - else: - assert 0 <= blackpoint <= midpoint <= whitepoint <= 255 + if image.mode != "L": + msg = f"mode must be L, not {image.mode}" + raise ValueError(msg) + if not 0 <= blackpoint <= whitepoint <= 255: + msg = ( + "blackpoint and whitepoint must each be between or equal to 0 and 255, " + "with blackpoint less than or equal to whitepoint" + ) + raise ValueError(msg) + if mid is not None and not blackpoint <= midpoint <= whitepoint: + msg = "midpoint must be between or equal to blackpoint and whitepoint" + raise ValueError(msg) # Define colors from arguments rgb_black = cast(Sequence[int], _color(black, "RGB"))