-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclean_images.py
146 lines (121 loc) · 4.51 KB
/
clean_images.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
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
import os
import shutil
import json
from PIL import Image
public_dir = "public"
images_dir = os.path.join(public_dir, "images")
images_backup_dir = "images-backup"
content_dir = os.path.join(public_dir, "content.json")
max_image_size = 256000
image_exts = ["jpg", "jpeg", "png", "svg", "webp"]
content_json = open(content_dir).read()
def get_images():
images = []
for subfolder in os.listdir(images_dir):
subfolder_path = os.path.join(images_dir, subfolder)
if os.path.isdir(subfolder_path):
for image in os.listdir(subfolder_path):
image_path = os.path.join(subfolder_path, image)
images.append(image_path)
return images
def remove_unused_images(images):
print("Removing Unused Images...")
unused_images = []
for image in images:
basename = os.path.basename(image)
if basename not in content_json:
unused_images.append(image)
os.remove(image)
print(f"- Removed: {image}")
for unused_image in unused_images:
images.remove(unused_image)
def convert_images_to_jpegs(images):
global content_json
print("Converting images to JPEGs...")
replacements = []
for image in images:
if image.endswith(".png") or image.endswith(".webp"):
basename = os.path.basename(image)
new_image = image.replace(".png", ".jpg")
new_image = new_image.replace(".webp", ".jpg")
new_basename = os.path.basename(new_image)
content_json = content_json.replace(basename, new_basename)
image_data = Image.open(image)
image_data = image_data.convert("RGB")
image_data.save(new_image, format="JPEG", quality=100)
os.remove(image)
replacements.append((image, new_image))
print(f"- Image to JPEG: {image} -> {new_image}")
for replacement in replacements:
images.remove(replacement[0])
images.append(replacement[1])
def normalize_names(images):
global content_json
print("Normalizing Image Names...")
replacements = []
for image in images:
basename = os.path.basename(image)
new_basename = basename
if image.endswith(".jpeg"):
new_basename = basename.replace(".jpeg", ".jpg")
new_basename = new_basename.lower()
new_basename = new_basename.replace("_", "-")
if new_basename != basename:
content_json = content_json.replace(basename, new_basename)
new_image = image.replace(basename, new_basename)
replacements.append((image, new_image))
os.rename(image, new_image)
print(f"- Normalized: {image} -> {new_image}")
for replacement in replacements:
images.remove(replacement[0])
images.append(replacement[1])
def compress_image(image):
quality = 95
resize_factor = 1
image_data = Image.open(image)
while True:
image_data.save(image, format="JPEG", quality=quality)
image_size = os.path.getsize(image)
if image_size <= max_image_size:
break
quality -= 5
if quality < 70:
quality = 95
resize_factor *= 2
image_data = image_data.resize(
(int(image_data.width / 2), int(image_data.height / 2)),
Image.BILINEAR,
)
return image_size, resize_factor, quality
def compress_large_images(images):
print("Compressing Large Images...")
for image in images:
if not image.endswith(".svg"):
image_size = os.path.getsize(image)
if image_size > max_image_size:
new_image_size, resize_factor, quality = compress_image(image)
change = (image_size - new_image_size) / image_size * 100
print(
f"- Compressed: {image} Resize=1/{resize_factor} "
f"Quality={quality} Change={change:.2f}%"
)
def minify_svgs(images):
print("Minifying SVGs...")
for image in images:
if image.endswith(".svg"):
os.system(f"npx svgo {image}")
def backup_public():
shutil.copytree(images_dir, images_backup_dir)
def save_content():
j = json.loads(content_json)
open(content_dir, "w").write(json.dumps(j, indent=2))
def clean_images():
images = get_images()
backup_public()
remove_unused_images(images)
convert_images_to_jpegs(images)
normalize_names(images)
compress_large_images(images)
minify_svgs(images)
save_content()
clean_images()