Last active
January 24, 2024 15:17
-
-
Save CodeByAidan/6b70a5828972012e62967576f3309a98 to your computer and use it in GitHub Desktop.
Convert an RGB tuple to a hexadecimal color code in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _rgb_to_hexadecimal( | |
rgb: tuple, include_prefix: bool = False, lowercase: bool = False | |
) -> str: | |
""" | |
Convert an RGB tuple to a hexadecimal color code. | |
Args: | |
rgb (tuple): The RGB tuple representing the color components. | |
include_prefix (bool, optional): Whether to include the '#' prefix in the hexadecimal color code. Defaults to False. | |
lowercase (bool, optional): Whether to use lowercase letters in the hexadecimal color code. Defaults to False. | |
Returns: | |
str: The hexadecimal color code. | |
Examples: | |
>>> _rgb_to_hexadecimal((255, 0, 128)) | |
'FF0080' | |
>>> _rgb_to_hexadecimal((255, 0, 128), include_prefix=True) | |
'#FF0080' | |
>>> _rgb_to_hexadecimal((255, 0, 128), lowercase=True) | |
'ff0080' | |
>>> _rgb_to_hexadecimal((255, 0, 128), include_prefix=True, lowercase=True) | |
'#ff0080' | |
""" | |
hex_string = ("{:06x}" if lowercase else "{:06X}").format( | |
sum( | |
c << (16 - i * 8) | |
for i, c in enumerate(map(lambda x: max(0, min(255, x)), rgb)) | |
) | |
) | |
return f"#{hex_string}" if include_prefix else hex_string |
Author
CodeByAidan
commented
Jan 24, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment