-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolorconv.py
More file actions
291 lines (202 loc) · 7.41 KB
/
Copy pathcolorconv.py
File metadata and controls
291 lines (202 loc) · 7.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3
"""Convert colors between HEX, RGB(A), HSL(A), and CMYK formats.
Usage: python3.14 colorconv.py COLOR [--hex|--rgb|--rgba|--hsl|--hsla|--cmyk]
For example: ``python3.14 colorconv.py '#336699' --hsl``.
"""
import argparse
import colorsys
import re
from dataclasses import dataclass
@dataclass
class Color:
r: int
g: int
b: int
a: float = 1.0
def clamp(self) -> "Color":
return Color(
r=max(0, min(255, round(self.r))),
g=max(0, min(255, round(self.g))),
b=max(0, min(255, round(self.b))),
a=max(0.0, min(1.0, self.a)),
)
def parse_number(value: str) -> float:
value = value.strip()
if value.endswith("%"):
return float(value[:-1]) / 100
return float(value)
def parse_alpha(value: str) -> float:
value = value.strip()
if value.endswith("%"):
return float(value[:-1]) / 100
return float(value)
def parse_rgb_component(value: str) -> int:
value = value.strip()
if value.endswith("%"):
return round(float(value[:-1]) / 100 * 255)
return round(float(value))
def split_args(content: str) -> list[str]:
return [part.strip() for part in content.split(",")]
def parse_hex(value: str) -> Color:
value = value.strip()
value = value.removeprefix("#")
if len(value) == 3:
r = int(value[0] * 2, 16)
g = int(value[1] * 2, 16)
b = int(value[2] * 2, 16)
return Color(r, g, b)
if len(value) == 4:
r = int(value[0] * 2, 16)
g = int(value[1] * 2, 16)
b = int(value[2] * 2, 16)
a = int(value[3] * 2, 16) / 255
return Color(r, g, b, a)
if len(value) == 6:
r = int(value[0:2], 16)
g = int(value[2:4], 16)
b = int(value[4:6], 16)
return Color(r, g, b)
if len(value) == 8:
r = int(value[0:2], 16)
g = int(value[2:4], 16)
b = int(value[4:6], 16)
a = int(value[6:8], 16) / 255
return Color(r, g, b, a)
raise ValueError("Invalid HEX format. Use #RGB, #RGBA, #RRGGBB or #RRGGBBAA.")
def parse_rgb(value: str) -> Color:
match = re.fullmatch(r"(rgba?|RGBA?)\((.*)\)", value.strip())
if not match:
raise ValueError("Invalid RGB/RGBA format.")
func_name = match.group(1).lower()
parts = split_args(match.group(2))
if func_name == "rgb" and len(parts) not in (3, 4):
raise ValueError("rgb() must contain 3 components, or 4 if alpha is used.")
if func_name == "rgba" and len(parts) != 4:
raise ValueError("rgba() must contain 4 components.")
r = parse_rgb_component(parts[0])
g = parse_rgb_component(parts[1])
b = parse_rgb_component(parts[2])
a = parse_alpha(parts[3]) if len(parts) == 4 else 1.0
return Color(r, g, b, a).clamp()
def parse_hsl(value: str) -> Color:
match = re.fullmatch(r"(hsla?|HSLA?)\((.*)\)", value.strip())
if not match:
raise ValueError("Invalid HSL/HSLA format.")
func_name = match.group(1).lower()
parts = split_args(match.group(2))
if func_name == "hsl" and len(parts) not in (3, 4):
raise ValueError("hsl() must contain 3 components, or 4 if alpha is used.")
if func_name == "hsla" and len(parts) != 4:
raise ValueError("hsla() must contain 4 components.")
h = float(parts[0].replace("deg", "").strip()) % 360
s = parse_number(parts[1])
lightness = parse_number(parts[2])
a = parse_alpha(parts[3]) if len(parts) == 4 else 1.0
r, g, b = colorsys.hls_to_rgb(h / 360, lightness, s)
return Color(
r=round(r * 255),
g=round(g * 255),
b=round(b * 255),
a=a,
).clamp()
def parse_cmyk(value: str) -> Color:
match = re.fullmatch(r"(cmyk|CMYK)\((.*)\)", value.strip())
if not match:
raise ValueError("Invalid CMYK format.")
parts = split_args(match.group(2))
if len(parts) not in (4, 5):
raise ValueError("cmyk() must contain 4 components, or 5 if alpha is used.")
c = parse_number(parts[0])
m = parse_number(parts[1])
y = parse_number(parts[2])
k = parse_number(parts[3])
a = parse_alpha(parts[4]) if len(parts) == 5 else 1.0
r = 255 * (1 - c) * (1 - k)
g = 255 * (1 - m) * (1 - k)
b = 255 * (1 - y) * (1 - k)
return Color(round(r), round(g), round(b), a).clamp()
def parse_color(value: str) -> Color:
value = value.strip()
if value.startswith("#") or re.fullmatch(r"[0-9a-fA-F]{3,8}", value):
return parse_hex(value)
lower = value.lower()
if lower.startswith("rgb"):
return parse_rgb(value)
if lower.startswith("hsl"):
return parse_hsl(value)
if lower.startswith("cmyk"):
return parse_cmyk(value)
raise ValueError("Unsupported input format.")
def format_hex(color: Color) -> str:
color = color.clamp()
if color.a < 1:
alpha = round(color.a * 255)
return f"#{color.r:02x}{color.g:02x}{color.b:02x}{alpha:02x}"
return f"#{color.r:02x}{color.g:02x}{color.b:02x}"
def format_rgb(color: Color) -> str:
color = color.clamp()
return f"rgb({color.r}, {color.g}, {color.b})"
def format_rgba(color: Color) -> str:
color = color.clamp()
return f"rgba({color.r}, {color.g}, {color.b}, {color.a:.3g})"
def format_hsl(color: Color, with_alpha: bool = False) -> str:
color = color.clamp()
r = color.r / 255
g = color.g / 255
b = color.b / 255
hue, lightness, saturation = colorsys.rgb_to_hls(r, g, b)
h_deg = round(hue * 360)
s_pct = round(saturation * 100)
l_pct = round(lightness * 100)
if with_alpha:
return f"hsla({h_deg}, {s_pct}%, {l_pct}%, {color.a:.3g})"
return f"hsl({h_deg}, {s_pct}%, {l_pct}%)"
def format_cmyk(color: Color) -> str:
color = color.clamp()
r = color.r / 255
g = color.g / 255
b = color.b / 255
k = 1 - max(r, g, b)
if k == 1:
c = m = y = 0
else:
c = (1 - r - k) / (1 - k)
m = (1 - g - k) / (1 - k)
y = (1 - b - k) / (1 - k)
return (
f"cmyk({round(c * 100)}%, "
f"{round(m * 100)}%, "
f"{round(y * 100)}%, "
f"{round(k * 100)}%)"
)
def main() -> None:
parser = argparse.ArgumentParser(
description="Convert CSS-like colors between HEX, RGB, RGBA, HSL, HSLA and CMYK."
)
parser.add_argument("color", help='Input color, for example: "rgb(0, 0, 0)"')
output = parser.add_mutually_exclusive_group(required=True)
output.add_argument("--hex", action="store_true", help="Convert to HEX")
output.add_argument("--rgb", action="store_true", help="Convert to RGB")
output.add_argument("--rgba", action="store_true", help="Convert to RGBA")
output.add_argument("--hsl", action="store_true", help="Convert to HSL")
output.add_argument("--hsla", action="store_true", help="Convert to HSLA")
output.add_argument("--cmyk", action="store_true", help="Convert to CMYK")
args = parser.parse_args()
try:
color = parse_color(args.color)
if args.hex:
print(format_hex(color))
elif args.rgb:
print(format_rgb(color))
elif args.rgba:
print(format_rgba(color))
elif args.hsl:
print(format_hsl(color))
elif args.hsla:
print(format_hsl(color, with_alpha=True))
elif args.cmyk:
print(format_cmyk(color))
except ValueError as error:
parser.error(str(error))
if __name__ == "__main__":
main()