Last active
March 5, 2024 23:02
-
-
Save aodin/738ae50965453554c745d48980f35153 to your computer and use it in GitHub Desktop.
Generate background colors for strings that will be displayed with white text
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
import colorsys | |
FNV_OFFSET = 0x811C9DC5 # 2166136261, FNV-1 32-bit offset basis | |
FNV_PRIME = 0x01000193 # FNV-1a 32-bit prime | |
def fnv1a_32(value: str) -> int: | |
""" | |
Compute the FNV-1a (32-bit) hash of a given data string. | |
https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function | |
""" | |
output = FNV_OFFSET | |
for v in value: | |
output ^= ord(v) | |
output *= FNV_PRIME | |
output &= 0xFFFFFFFF # Use 32-bit arithmetic | |
return output | |
def to_hsl(v: int) -> tuple[int, int, int]: | |
# Extract HSL components from the integer hash value | |
return (v >> 20) & 0xFF, (v >> 12) & 0xFF, (v >> 4) & 0xFF | |
def background_color(value: str) -> str: | |
""" | |
Returns an RGB hex code for the string, which is usable as a background color when using white text. | |
""" | |
h, s, l = to_hsl(fnv1a_32(value)) | |
r, g, b = colorsys.hls_to_rgb(h / 255, (l / 255) * 0.3 + 0.2, s / 255) | |
return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment