-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_thumbnails.py
More file actions
51 lines (43 loc) · 2.01 KB
/
generate_thumbnails.py
File metadata and controls
51 lines (43 loc) · 2.01 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
# 这是一个针对相册压缩成缩略图的python程序,目前需要针对指定的相册文件手动运行
# 运行模式:python generate_thumbnails.py public/pictures/Albums/NewZealand public/pictures/thumbnails/NewZealand
import os
import sys
from PIL import Image, ExifTags
def create_thumbnail(image_path, output_path, size=(500, 500)):
with Image.open(image_path) as img:
# 处理图片方向
try:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
exif = dict(img._getexif().items())
if exif[orientation] == 3:
img = img.rotate(180, expand=True)
elif exif[orientation] == 6:
img = img.rotate(270, expand=True)
elif exif[orientation] == 8:
img = img.rotate(90, expand=True)
except (AttributeError, KeyError, IndexError):
# 图片没有 EXIF 信息,不需要旋转
pass
# 计算缩放比例
img.thumbnail((size[0], size[1]), Image.LANCZOS)
# 保存时不添加白边,保持原有比例
img.save(output_path, "WEBP", quality=95)
def process_directory(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.webp')):
input_path = os.path.join(input_dir, filename)
output_filename = os.path.splitext(filename)[0] + "_thumb.webp"
output_path = os.path.join(output_dir, output_filename)
create_thumbnail(input_path, output_path)
print(f"Created thumbnail for {filename}")
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python generate_thumbnails.py <input_directory> <output_directory>")
sys.exit(1)
input_dir = sys.argv[1]
output_dir = sys.argv[2]
process_directory(input_dir, output_dir)