Skip to content

Commit e8e6b54

Browse files
committed
add script for conversion to webp
1 parent 154eb9a commit e8e6b54

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

convert_to_webp.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from pathlib import Path
2+
from PIL import Image
3+
import os.path
4+
from termcolor import colored
5+
6+
total_saved_size = 0
7+
8+
def sizeof_fmt(num, suffix="B"):
9+
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
10+
if abs(num) < 1024.0:
11+
return f"{num:3.1f}{unit}{suffix}"
12+
num /= 1024.0
13+
return f"{num:.1f}Yi{suffix}"
14+
15+
def convert_to_webp_if_need(source):
16+
global total_saved_size
17+
destination = source.with_suffix(".webp")
18+
19+
if not os.path.isfile(destination):
20+
image = Image.open(source)
21+
size_before = os.path.getsize(source)
22+
image.save(destination, format="webp", method=6, lossless=True)
23+
size_after = os.path.getsize(destination)
24+
diff = size_before - size_after
25+
color = "green" if diff > 0 else "red"
26+
print("Convert to WEBP: " + str(destination) + " " + colored(sizeof_fmt(diff), color))
27+
total_saved_size = total_saved_size + diff
28+
return destination
29+
30+
31+
def main():
32+
global total_saved_size
33+
paths = Path(".").glob("**/*.png")
34+
for path in paths:
35+
convert_to_webp_if_need(path)
36+
# paths = Path(".").glob("**/*.jpg")
37+
# for path in paths:
38+
# convert_to_webp_if_need(path)
39+
color = "green" if total_saved_size > 0 else "red"
40+
print(colored("Total saved size is "+sizeof_fmt(total_saved_size), color))
41+
42+
main()

0 commit comments

Comments
 (0)