diff --git a/supervision/draw/color.py b/supervision/draw/color.py index 69bcc9c5..9d1b4ad9 100644 --- a/supervision/draw/color.py +++ b/supervision/draw/color.py @@ -71,6 +71,21 @@ class Color: r, g, b = (int(color_hex[i : i + 2], 16) for i in range(0, 6, 2)) return cls(r, g, b) + def as_hex(self) -> str: + """ + Converts the Color instance to a hex string. + + Returns: + str: The hexadecimal color string. + + Example: + ``` + >>> Color(r=255, g=0, b=255).as_hex() + '#ff00ff' + ``` + """ + return f"#{self.r:02x}{self.g:02x}{self.b:02x}" + def as_rgb(self) -> Tuple[int, int, int]: """ Returns the color as an RGB tuple. diff --git a/test/draw/test_color.py b/test/draw/test_color.py index 723f7043..eb4c3657 100644 --- a/test/draw/test_color.py +++ b/test/draw/test_color.py @@ -30,3 +30,22 @@ def test_color_from_hex( with exception: result = Color.from_hex(color_hex=color_hex) assert result == expected_result + + +@pytest.mark.parametrize( + "color, expected_result, exception", + [ + (Color.white(), "#ffffff", DoesNotRaise()), + (Color.black(), "#000000", DoesNotRaise()), + (Color.red(), "#ff0000", DoesNotRaise()), + (Color.green(), "#00ff00", DoesNotRaise()), + (Color.blue(), "#0000ff", DoesNotRaise()), + (Color(r=128, g=128, b=0), "#808000", DoesNotRaise()), + ], +) +def test_color_as_hex( + color: Color, expected_result: Optional[str], exception: Exception +) -> None: + with exception: + result = color.as_hex() + assert result == expected_result