diff --git a/src/zimscraperlib/image/probing.py b/src/zimscraperlib/image/probing.py index 6a8d2634..935dd24b 100644 --- a/src/zimscraperlib/image/probing.py +++ b/src/zimscraperlib/image/probing.py @@ -16,15 +16,21 @@ known_extensions.update(PIL_FMT_EXTENSION) +def format_rgb(r: int, g: int, b: int) -> str: + """#RRGGBB for an RGB triple, with each channel clamped to 0-255. + + ColorThief and the solarize step can return a channel of 256. Formatting + that with hex() emits three digits, which is not a CSS color. + """ + channels = (max(0, min(255, int(channel))) for channel in (r, g, b)) + return "#" + "".join(f"{channel:02X}" for channel in channels) + + def get_colors( src: pathlib.Path, *, use_palette: bool | None = True ) -> tuple[str, str]: """(main, secondary) HTML color codes from an image path""" - def rgb_to_hex(r: int, g: int, b: int) -> str: - """hexadecimal HTML-friendly color code for RGB tuple""" - return "#{}{}{}".format(*[str(hex(x)[2:]).zfill(2) for x in (r, g, b)]).upper() - def solarize(r: int, g: int, b: int) -> tuple[int, int, int]: # calculate solarized color for main h, _, s = colorsys.rgb_to_hls(float(r) / 256, float(g) / 256, float(b) / 256) @@ -49,11 +55,11 @@ def solarize(r: int, g: int, b: int) -> tuple[int, int, int]: ) sr, sg, sb = solarize(mr, mg, mb) # pyright: ignore[reportUnknownArgumentType] - return rgb_to_hex( + return format_rgb( mr, # pyright: ignore[reportUnknownArgumentType] mg, # pyright: ignore[reportUnknownArgumentType] mb, # pyright: ignore[reportUnknownArgumentType] - ), rgb_to_hex(sr, sg, sb) + ), format_rgb(sr, sg, sb) def is_hex_color(text: str) -> bool: diff --git a/tests/image/test_color_range.py b/tests/image/test_color_range.py new file mode 100644 index 00000000..6bb65c33 --- /dev/null +++ b/tests/image/test_color_range.py @@ -0,0 +1,25 @@ +"""Theme colors must stay valid CSS hex even when a channel is outside 0-255.""" + +import pathlib + +from PIL import Image + +from zimscraperlib.image.probing import format_rgb, get_colors, is_hex_color + + +def test_format_rgb_clamps_channels_outside_a_byte(): + assert format_rgb(256, 4, -1) == "#FF0400" + assert format_rgb(4, 101, 155) == "#04659B" + assert is_hex_color(format_rgb(256, 256, 256)) + + +def test_theme_colors_from_a_pure_red_image_are_hex(tmp_path: pathlib.Path): + path = tmp_path / "red.png" + Image.new("RGB", (32, 32), (255, 0, 0)).save(path) + + for use_palette in (False, True): + main, secondary = get_colors(path, use_palette=use_palette) + assert is_hex_color(main), main + assert is_hex_color(secondary), secondary + assert len(main) == 7 + assert len(secondary) == 7