Last active
January 11, 2023 13:42
-
-
Save eyenalxai/41a6e01b62dc24325e0accb3f04d489e to your computer and use it in GitHub Desktop.
HSL to HEX
This file contains hidden or 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 hsl_to_hex(hue: int, saturation_percent: int, lightness_percent: int) -> str: | |
red, green, blue = hsl_to_rgb( | |
hue=hue, | |
saturation_percent=saturation_percent, | |
lightness_percent=lightness_percent, | |
) | |
return rgb_to_hex(red=red, green=green, blue=blue) | |
def rgb_to_hex(red: int, green: int, blue: int) -> str: | |
return "#{red:02x}{green:02x}{blue:02x}".format(red=red, green=green, blue=blue) | |
def hsl_to_rgb( | |
hue: int, saturation_percent: int, lightness_percent: int | |
) -> tuple[int, int, int]: | |
saturation = saturation_percent / 100 | |
lightness = lightness_percent / 100 | |
def f(n: int) -> int: | |
k = (n + hue / 30) % 12 | |
a = saturation * min(lightness, 1 - lightness) | |
return round((lightness - a * max(-1.0, min(k - 3, 9 - k, 1))) * 255) | |
red = f(n=0) | |
green = f(n=8) | |
blue = f(n=4) | |
return red, green, blue | |
def test_hsl_to_hex() -> None: | |
hue = 0 | |
saturation_percent = 79 | |
lightness_percent = 58 | |
test_hex = "#e93f3f" | |
calculated_hex = hsl_to_hex( | |
hue=hue, | |
saturation_percent=saturation_percent, | |
lightness_percent=lightness_percent, | |
) | |
print("test_hex: {test_hex}".format(test_hex=test_hex)) | |
print("calculated_hex: {calculated_hex}".format(calculated_hex=calculated_hex)) | |
if __name__ == "__main__": | |
test_hsl_to_hex() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment