/
gen_thumbnail.py
58 lines (46 loc) · 1.64 KB
/
gen_thumbnail.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
import blurhash
import json
from datetime import datetime
from PIL import Image
from pathlib import Path
from itertools import chain
REF_WIDTH = 600
JSON_NAME = "images.json"
ARCHIVES = ["blog", "chaotic", "fine-weather"]
def run():
for p in Path().glob("**/thumbnail/*"):
p.unlink()
for p in Path().glob("**/images.json"):
p.unlink()
for archive in ARCHIVES:
folder_path = Path(archive)
processed = {}
images_json_path = folder_path / JSON_NAME
if images_json_path.exists():
with open(images_json_path, "rt", encoding="utf-8") as f:
processed = json.load(f)
for img_path in list(
chain.from_iterable(
[folder_path.glob(f"**/*.{i}") for i in ["png", "jpg", "jpeg"]]
)
):
path_str = str(img_path)
if path_str not in processed:
img = Image.open(img_path)
w, h = img.size
img.thumbnail((REF_WIDTH, round(REF_WIDTH / w * h)))
thumbnail_folder = folder_path / "thumbnail"
thumbnail_folder.mkdir(exist_ok=True, parents=True)
img.save(thumbnail_folder / img_path.name)
hash = blurhash.encode(img, 4, 4)
processed[path_str] = {
"hash": hash,
"size": [w, h],
}
processed["version"] = {
"update_time": datetime.now().strftime("%Y/%m/%d %H:%M:%S")
}
with open(images_json_path, "wt", encoding="utf-8") as f:
f.write(json.dumps(processed))
if __name__ == "__main__":
run()