rgb_to_hex python snippet. #1

Merged
ld merged 1 commits from rgb_to_hex into main 2025-03-31 20:26:19 +08:00
Showing only changes of commit 641e53b1a5 - Show all commits

50
python/rgb_to_hex.py Normal file
View File

@ -0,0 +1,50 @@
def rgb_to_hex(r, g, b, a=None, bg=255, prefix="#"):
"""
Convert given RGB color decimals or floats to Hex string.
Parameters
---
r, g, b: float | int
Corresponding channel value. Support decimal or float.
a: float | None, Default: None
Alpha value for generate simulated transparent color.
If specified, the returned hex color should looks like
rendered as `a` alpha value, on the given background `bg`.
Default to None, which means disable simuating transparent.
bg: int, Default: 255
If `a` is specified, `bg` will be used as the background
for render transparent color.
Default to 255, which means 'white' background.
Examples
---
>>> rgb_to_hex(255, 0, 255)
'#FF00FF'
>>> rgb_to_hex(255, 255, 0, a=0.0625, bg=0)
'#0F0F00'
"""
def to_decimal(v, base=255) -> int:
if isinstance(v, float) and v <= 1:
v *= base
return int(v)
def patch_alpha(v, alpha, bg=255):
return int(v * alpha + bg * (1 - alpha))
r = to_decimal(r)
g = to_decimal(g)
b = to_decimal(b)
if a is not None:
r = patch_alpha(r, a, bg)
g = patch_alpha(g, a, bg)
b = patch_alpha(b, a, bg)
if prefix is None:
prefix = ""
return f"{prefix}{r:02X}{g:02X}{b:02X}"