-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvg_optimizer.py
More file actions
476 lines (377 loc) · 16.6 KB
/
svg_optimizer.py
File metadata and controls
476 lines (377 loc) · 16.6 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
"""
SVG Optimizer for Pixel-Perfect Small Size Display
Creates pixel-grid-aligned versions optimized for favicon/icon sizes
"""
import re
import xml.etree.ElementTree as ET
from typing import Tuple, List
def round_svg_coordinates(svg_content: str, grid_size: float = 1.0) -> str:
"""
Round all SVG path coordinates to pixel grid for crisp small-size rendering.
Args:
svg_content: The SVG file content as string
grid_size: The grid size to snap to (1.0 = whole pixels)
Returns:
SVG content with rounded coordinates
"""
def round_number(match):
"""Round a floating point number to the grid"""
num = float(match.group(0))
rounded = round(num / grid_size) * grid_size
# Return as integer if it's a whole number, otherwise with minimal decimals
if rounded == int(rounded):
return str(int(rounded))
return f"{rounded:.1f}"
# Find all path elements - use proper regex to match only path d attributes
# Match: whitespace + d=" to avoid matching id="
def process_path(match):
prefix = match.group(1) # The whitespace before d=
path_data = match.group(2)
# Match all numbers (including negative and decimals)
processed = re.sub(r'-?\d+\.?\d*', round_number, path_data)
return f'{prefix}d="{processed}"'
# Process all path d attributes (with whitespace before d to avoid id, etc.)
result = re.sub(r'(\s)d="([^"]+)"', process_path, svg_content)
return result
def normalize_viewbox(svg_content: str, target_size: int = 64, force_square: bool = True) -> str:
"""
Set display size, optionally forcing perfect square output with centered content.
Args:
svg_content: The SVG file content
target_size: Target display size (both width and height if force_square=True)
force_square: If True, creates perfect square output with centered content
Returns:
SVG with updated width/height and viewBox for perfect square rendering
"""
try:
# Extract current viewBox
viewbox_match = re.search(r'viewBox="([^"]+)"', svg_content)
if not viewbox_match:
# No viewBox, try to get from width/height
width_match = re.search(r'width="(\d+)"', svg_content)
height_match = re.search(r'height="(\d+)"', svg_content)
if width_match and height_match:
w, h = float(width_match.group(1)), float(height_match.group(1))
viewbox_str = f"0 0 {int(w)} {int(h)}"
svg_content = re.sub(r'<svg', f'<svg viewBox="{viewbox_str}"', svg_content, count=1)
else:
# Can't determine size
return svg_content
viewbox_match = re.search(r'viewBox="([^"]+)"', svg_content)
old_viewbox = viewbox_match.group(1)
vb_parts = old_viewbox.split()
min_x, min_y, vb_width, vb_height = map(float, vb_parts)
if force_square:
# PERFECT SQUARE: Adjust viewBox to create square canvas with centered content
max_dim = max(vb_width, vb_height)
# Calculate offsets to center the content
if vb_width < max_dim:
# Portrait or needs horizontal centering - add padding to sides
x_offset = (max_dim - vb_width) / 2
new_min_x = min_x - x_offset
new_vb_width = max_dim
else:
new_min_x = min_x
new_vb_width = vb_width
if vb_height < max_dim:
# Landscape or needs vertical centering - add padding to top/bottom
y_offset = (max_dim - vb_height) / 2
new_min_y = min_y - y_offset
new_vb_height = max_dim
else:
new_min_y = min_y
new_vb_height = vb_height
# Ensure viewBox is perfectly square
square_dim = max(new_vb_width, new_vb_height)
final_viewbox = f"{new_min_x} {new_min_y} {square_dim} {square_dim}"
# Update viewBox to square
result = re.sub(r'viewBox="[^"]*"', f'viewBox="{final_viewbox}"', svg_content)
# Set display size to perfect square
result = re.sub(r'width="[^"]*"', f'width="{target_size}"', result)
result = re.sub(r'height="[^"]*"', f'height="{target_size}"', result)
else:
# Original behavior - preserve aspect ratio
max_dim = max(vb_width, vb_height)
scale_factor = target_size / max_dim
display_width = int(vb_width * scale_factor)
display_height = int(vb_height * scale_factor)
result = re.sub(r'width="[^"]*"', f'width="{display_width}"', svg_content)
result = re.sub(r'height="[^"]*"', f'height="{display_height}"', result)
return result
except Exception as e:
print(f"Error normalizing viewBox: {e}")
return svg_content
def simplify_paths(svg_content: str, tolerance: float = 0.5) -> str:
"""
Remove points that are very close together to reduce path complexity.
Args:
svg_content: The SVG content
tolerance: Minimum distance between points to keep
Returns:
SVG with simplified paths
"""
# This is a simple implementation that removes consecutive duplicate points
# A more sophisticated version would use Douglas-Peucker algorithm
def simplify_path_data(match):
prefix = match.group(1) # The whitespace before d=
path_data = match.group(2)
# Split into commands and coordinates
# This is a simplified approach - just remove very close consecutive points
parts = re.split(r'([A-Za-z])', path_data)
result = []
prev_x, prev_y = None, None
for part in parts:
if not part.strip():
continue
if part in 'MmLlHhVvCcSsQqTtAaZz':
result.append(part)
else:
# Coordinate data
coords = re.findall(r'-?\d+\.?\d*', part)
filtered_coords = []
i = 0
while i < len(coords):
if i + 1 < len(coords):
x, y = float(coords[i]), float(coords[i + 1])
# Check if this point is too close to previous
if prev_x is not None and prev_y is not None:
dist = ((x - prev_x) ** 2 + (y - prev_y) ** 2) ** 0.5
if dist < tolerance:
i += 2
continue
filtered_coords.extend([coords[i], coords[i + 1]])
prev_x, prev_y = x, y
i += 2
else:
filtered_coords.append(coords[i])
i += 1
if filtered_coords:
result.append(','.join(filtered_coords))
return f'{prefix}d="{" ".join(result)}"'
return re.sub(r'(\s)d="([^"]+)"', simplify_path_data, svg_content)
def convert_curves_to_lines(svg_content: str) -> str:
"""
Convert Bezier curves to straight lines for crisp small-size rendering.
This dramatically simplifies paths for tiny icons.
Args:
svg_content: The SVG content
Returns:
SVG with curves converted to lines
"""
def simplify_path(match):
prefix = match.group(1)
path_data = match.group(2)
# Tokenize the path data
tokens = re.findall(r'[A-Za-z]|[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', path_data)
result = []
i = 0
while i < len(tokens):
if i >= len(tokens):
break
token = tokens[i]
# Check if this is a command (letter)
if not token[0].isalpha():
# Skip stray numbers
i += 1
continue
cmd = token
# Commands that we keep as-is (no parameters or simple parameters)
if cmd == 'Z' or cmd == 'z':
result.append(cmd)
i += 1
# Move command (M/m)
elif cmd in 'Mm':
result.append(cmd)
i += 1
# Consume x,y pairs until next command
while i + 1 < len(tokens) and not tokens[i][0].isalpha():
result.append(f'{tokens[i]},{tokens[i+1]}')
i += 2
# Line commands (L/l)
elif cmd in 'Ll':
result.append(cmd)
i += 1
while i + 1 < len(tokens) and not tokens[i][0].isalpha():
result.append(f'{tokens[i]},{tokens[i+1]}')
i += 2
# Horizontal/Vertical lines (H/h/V/v)
elif cmd in 'HhVv':
result.append(cmd)
i += 1
while i < len(tokens) and not tokens[i][0].isalpha():
result.append(tokens[i])
i += 1
# Cubic Bezier (C/c): 6 params -> convert to L with just endpoint
elif cmd in 'Cc':
line_cmd = 'L' if cmd.isupper() else 'l'
i += 1
# Process all cubic curve segments (groups of 6 numbers)
while i + 5 < len(tokens) and not tokens[i][0].isalpha():
# Skip control points (first 4 numbers), take endpoint (last 2)
end_x = tokens[i + 4]
end_y = tokens[i + 5]
result.append(line_cmd)
result.append(f'{end_x},{end_y}')
i += 6
# Smooth cubic (S/s): 4 params -> convert to L with endpoint
elif cmd in 'Ss':
line_cmd = 'L' if cmd.isupper() else 'l'
i += 1
while i + 3 < len(tokens) and not tokens[i][0].isalpha():
end_x = tokens[i + 2]
end_y = tokens[i + 3]
result.append(line_cmd)
result.append(f'{end_x},{end_y}')
i += 4
# Quadratic Bezier (Q/q): 4 params -> convert to L
elif cmd in 'Qq':
line_cmd = 'L' if cmd.isupper() else 'l'
i += 1
while i + 3 < len(tokens) and not tokens[i][0].isalpha():
end_x = tokens[i + 2]
end_y = tokens[i + 3]
result.append(line_cmd)
result.append(f'{end_x},{end_y}')
i += 4
# Smooth quadratic (T/t): 2 params -> convert to L
elif cmd in 'Tt':
line_cmd = 'L' if cmd.isupper() else 'l'
i += 1
while i + 1 < len(tokens) and not tokens[i][0].isalpha():
result.append(line_cmd)
result.append(f'{tokens[i]},{tokens[i+1]}')
i += 2
# Arc (A/a): 7 params -> convert to L with endpoint
elif cmd in 'Aa':
line_cmd = 'L' if cmd.isupper() else 'l'
i += 1
while i + 6 < len(tokens) and not tokens[i][0].isalpha():
end_x = tokens[i + 5]
end_y = tokens[i + 6]
result.append(line_cmd)
result.append(f'{end_x},{end_y}')
i += 7
else:
# Unknown command, skip
i += 1
return f'{prefix}d="{" ".join(result)}"'
return re.sub(r'(\s)d="([^"]+)"', simplify_path, svg_content)
def clean_degenerate_moves(svg_content: str) -> str:
"""
Remove degenerate moves (0,0) and redundant commands from paths.
Args:
svg_content: The SVG content
Returns:
SVG with cleaned paths
"""
def clean_path(match):
prefix = match.group(1)
path_data = match.group(2)
# Remove sequences like "l 0,0" or "L 0,0"
cleaned = re.sub(r'[lL]\s+0,0\s*', '', path_data)
# Remove isolated command letters (commands with no coordinates)
# Match a command letter followed by another command letter or end
cleaned = re.sub(r'([LlMmHhVvCcSsQqTt])\s+(?=[LlMmHhVvCcSsQqTtAaZz]|$)', '', cleaned)
# Remove multiple consecutive spaces
cleaned = re.sub(r'\s+', ' ', cleaned)
# Remove spaces before and after commas
cleaned = re.sub(r'\s*,\s*', ',', cleaned)
# Trim
cleaned = cleaned.strip()
return f'{prefix}d="{cleaned}"'
return re.sub(r'(\s)d="([^"]+)"', clean_path, svg_content)
def decimate_path_points(svg_content: str, keep_every_n: int = 3) -> str:
"""
Drastically reduce path complexity by keeping only every Nth point.
Critical for tiny icons where detail is impossible to see anyway.
Args:
svg_content: The SVG content
keep_every_n: Keep every Nth line command
Returns:
SVG with decimated paths
"""
def decimate_path(match):
prefix = match.group(1)
path_data = match.group(2)
tokens = re.findall(r'[A-Za-z]|[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?', path_data)
result = []
i = 0
line_count = 0
while i < len(tokens):
if i >= len(tokens):
break
token = tokens[i]
if not token[0].isalpha():
i += 1
continue
cmd = token
# Always keep M, Z commands
if cmd in 'MmZz':
result.append(cmd)
i += 1
if cmd in 'Mm' and i + 1 < len(tokens) and not tokens[i][0].isalpha():
result.append(f'{tokens[i]},{tokens[i+1]}')
i += 2
# Decimate L commands - keep only every Nth
elif cmd in 'Ll':
i += 1
if i + 1 < len(tokens) and not tokens[i][0].isalpha():
if line_count % keep_every_n == 0:
result.append(cmd)
result.append(f'{tokens[i]},{tokens[i+1]}')
line_count += 1
i += 2
else:
# Skip other commands
i += 1
return f'{prefix}d="{" ".join(result)}"'
return re.sub(r'(\s)d="([^"]+)"', decimate_path, svg_content)
def optimize_for_small_size(svg_content: str, target_size: int = 64) -> str:
"""
Full optimization pipeline for small-size display.
Creates a pixel-perfect version optimized for favicon/icon sizes by:
1. Normalizing viewBox to clean pixel size
2. Converting curves to straight lines (for very small sizes)
3. Drastically reducing point count (for very small sizes)
4. Rounding coordinates to pixel grid
5. Simplifying paths
6. Cleaning degenerate moves
Args:
svg_content: Original SVG content
target_size: Target size in pixels (32, 64, etc.)
Returns:
Optimized SVG content
"""
# Step 1: Normalize viewBox
optimized = normalize_viewbox(svg_content, target_size)
# Step 2: Keep curves for all sizes - they scale better than lines
# (Disabled curve-to-line conversion entirely)
# Step 3: Skip decimation - it's too destructive for logos
# The simplify_paths step below will remove redundant points more intelligently
# Step 4: Round coordinates to pixel grid
# Use ultra-fine sub-pixel precision for small sizes to preserve smooth curves
if target_size <= 16:
# Ultra-fine precision for 16px (0.001 = thousandths of a pixel)
optimized = round_svg_coordinates(optimized, grid_size=0.001)
elif target_size <= 32:
# Very fine precision for 32px
optimized = round_svg_coordinates(optimized, grid_size=0.005)
elif target_size <= 64:
# Fine precision for 64px
optimized = round_svg_coordinates(optimized, grid_size=0.01)
else:
# Standard sub-pixel precision for larger sizes
optimized = round_svg_coordinates(optimized, grid_size=0.05)
# Step 5: Simplify paths - DISABLED
# Path simplification removes details, even at tiny sizes
# Let the browser handle rendering optimization instead
# Step 6: Clean up degenerate moves and double commands
optimized = clean_degenerate_moves(optimized)
# Step 7: Add rendering hints for smooth, anti-aliased rendering
# Use geometricPrecision for smooth curves at all sizes
svg_tag_match = re.search(r'<svg[^>]*>', optimized)
if svg_tag_match and 'shape-rendering' not in svg_tag_match.group(0):
# geometricPrecision = smooth anti-aliased rendering
# auto = browser decides (usually smooth for curves)
optimized = optimized.replace('<svg ', '<svg shape-rendering="geometricPrecision" ', 1)
return optimized