Fix UnboundLocalError in _border for invalid tuple lengths and document rgba() color format

The _border helper in ImageOps raised UnboundLocalError when given a tuple
with a length other than 2 or 4 (e.g. 1-tuple or 3-tuple). This changes
it to raise a clear ValueError instead.

Also adds documentation for the rgba() color format in ImageColor, which
was supported in code and tested but missing from the docs.
This commit is contained in:
Varun Chawla 2026-02-13 19:38:48 -08:00
parent f78663b806
commit f708c00527
3 changed files with 14 additions and 0 deletions

View File

@ -256,6 +256,13 @@ def test_expand_palette(border: int | tuple[int, int, int, int]) -> None:
assert_image_equal(im_cropped, im)
@pytest.mark.parametrize("border", ((1,), (1, 2, 3), (1, 2, 3, 4, 5)))
def test_expand_invalid_border(border: tuple[int, ...]) -> None:
im = Image.new("1", (1, 1))
with pytest.raises(ValueError):
ImageOps.expand(im, border)
def test_colorize_2color() -> None:
# Test the colorizing function with 2-color functionality

View File

@ -27,6 +27,10 @@ The ImageColor module supports the following string formats:
as three percentages (0% to 100%). For example, ``rgb(255,0,0)`` and
``rgb(100%,0%,0%)`` both specify pure red.
* RGBA functions, given as ``rgba(red, green, blue, alpha)`` where the color
values and the alpha value are integers in the range 0 to 255. For example,
``rgba(255,0,0,128)`` specifies pure red with 50% opacity.
* Hue-Saturation-Lightness (HSL) functions, given as ``hsl(hue, saturation%,
lightness%)`` where hue is the color given as an angle between 0 and 360
(red=0, green=120, blue=240), saturation is a value between 0% and 100%

View File

@ -36,6 +36,9 @@ def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
left, top = right, bottom = border
elif len(border) == 4:
left, top, right, bottom = border
else:
msg = "border must be an integer or a 2- or 4-tuple"
raise ValueError(msg)
else:
left = top = right = bottom = border
return left, top, right, bottom