-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolorize_svg.py
101 lines (81 loc) · 2.81 KB
/
colorize_svg.py
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
import argparse
import platform
import subprocess
import tempfile
import os
import sys
# TODO: add support for 3 digit hex colors
# TODO: Move to utils.py
def is_hex_color(color):
return bool(
color.startswith("#")
and len(color) == 7
and all(c in "0123456789ABCDEFabcdef" for c in color[1:])
)
# TODO: add support for 3 digit hex colors
# TODO: Move to utils.py
def hex_to_rgb(hexcolor):
hexcolor = hexcolor.lstrip("#")
return tuple(int(hexcolor[i : i + 2], 16) for i in (0, 2, 4))
def colorize_svg(input_svg, output_svg, color):
print(f"Input SVG: {input_svg}")
print(f"Color: {color}")
print(f"Output SVG: {output_svg}")
if is_hex_color(color):
red, green, blue = hex_to_rgb(color)
else:
red, green, blue = map(int, color.split(","))
print(f"Red: {red}, Green: {green}, Blue: {blue}")
with tempfile.NamedTemporaryFile(delete=False, suffix=".svg") as temp_grayscale_svg:
temp_grayscale_svg_path = temp_grayscale_svg.name
try:
# Check if input file exists
if not os.path.isfile(input_svg):
print(f"Error: Input file '{input_svg}' does not exist.")
sys.exit(1)
# TODO: Convert SVG styles to attributes with SVGO (or similar)
# Convert to grayscale using svgray
print("Converting to grayscale...")
with open(temp_grayscale_svg_path, "w") as f:
subprocess.run(
[
sys.executable,
"./submodules/svgray/.svgray.py",
input_svg,
],
check=True,
stdout=f,
)
# Add color using svgshift
print("Adding color...")
with open(output_svg, "w") as f:
subprocess.run(
[
# ./svgshift-<your-environment>.exe (ubuntu or windows)
f"./svgshift-{platform.system().lower()}.exe",
"addrgb",
str(red),
str(green),
str(blue),
temp_grayscale_svg_path,
],
stdout=f,
check=True,
)
print(f"Colorized SVG saved as {output_svg}")
finally:
print("Cleaning up...")
os.remove(temp_grayscale_svg_path)
def main(args=None):
parser = argparse.ArgumentParser(description="Colorize SVG script")
parser.add_argument("input_svg", help="Input SVG file")
parser.add_argument("output_svg", help="Output SVG file")
parser.add_argument(
"--color",
required=True,
help="Color in hex (e.g., #FF5733) or RGB (e.g., 255,125,0) format",
)
args = parser.parse_args(args)
colorize_svg(args.input_svg, args.output_svg, args.color)
if __name__ == "__main__":
main()