1import colorsys
2import sys
3
4def hex_to_rgb(hex):
5 hex = hex.lstrip('#')
6 if len(hex) == 8: # 8 digit hex color
7 r, g, b, a = (int(hex[i:i+2], 16) for i in (0, 2, 4, 6))
8 return r, g, b, a / 255.0
9 else: # 6 digit hex color
10 return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)) + (1.0,)
11
12def rgb_to_hsla(rgb):
13 h, l, s = colorsys.rgb_to_hls(rgb[0]/255.0, rgb[1]/255.0, rgb[2]/255.0)
14 a = rgb[3] # alpha value
15 return (round(h * 360, 1), round(s * 100, 1), round(l * 100, 1), round(a, 3))
16
17def hex_to_hsla(hex):
18 return rgb_to_hsla(hex_to_rgb(hex))
19
20if len(sys.argv) != 2:
21 print("Usage: python util/hex_to_hsla.py <6 or 8 digit hex color or comma-separated list of colors>")
22else:
23 input_arg = sys.argv[1]
24 if ',' in input_arg: # comma-separated list of colors
25 hex_colors = input_arg.split(',')
26 hslas = [] # output array
27 for hex_color in hex_colors:
28 hex_color = hex_color.strip("'\" ")
29 h, s, l, a = hex_to_hsla(hex_color)
30 hslas.append(f"hsla({h} / 360., {s} / 100., {l} / 100., {a})")
31 print(hslas)
32 else: # single color
33 hex_color = input_arg.strip("'\"")
34 h, s, l, a = hex_to_hsla(hex_color)
35 print(f"hsla({h} / 360., {s} / 100., {l} / 100., {a})")