-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresize.py
More file actions
154 lines (126 loc) · 5.02 KB
/
Copy pathresize.py
File metadata and controls
154 lines (126 loc) · 5.02 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
图片批量压缩和调整大小脚本
- 等比例缩放
- 转换为JPG格式
- 宽度或高度最大1000px
- 质量保持95%
"""
import os
from PIL import Image
from pathlib import Path
def resize_image(input_path, output_path, max_dimension=1000, quality=95):
"""
调整图片大小并转换为JPG格式
参数:
input_path: 输入图片路径
output_path: 输出图片路径
max_dimension: 最大宽度或高度 (默认1000)
quality: JPG质量 (默认95)
"""
try:
# 打开图片
with Image.open(input_path) as img:
# 如果是RGBA模式(带透明通道),转换为RGB
if img.mode in ('RGBA', 'LA', 'P'):
# 创建白色背景
background = Image.new('RGB', img.size, (255, 255, 255))
if img.mode == 'P':
img = img.convert('RGBA')
background.paste(img, mask=img.split()[-1] if img.mode in ('RGBA', 'LA') else None)
img = background
elif img.mode != 'RGB':
img = img.convert('RGB')
# 获取原始尺寸
width, height = img.size
# 计算新尺寸(等比例缩放)
if width > max_dimension or height > max_dimension:
if width > height:
# 宽度更大,按宽度缩放
new_width = max_dimension
new_height = int(height * (max_dimension / width))
else:
# 高度更大,按高度缩放
new_height = max_dimension
new_width = int(width * (max_dimension / height))
# 调整大小,使用高质量的LANCZOS重采样
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
print(f" 调整尺寸: {width}x{height} -> {new_width}x{new_height}")
else:
print(f" 保持原尺寸: {width}x{height} (已符合要求)")
# 保存为JPG格式
img.save(output_path, 'JPEG', quality=quality, optimize=True)
# 显示文件大小变化
original_size = os.path.getsize(input_path) / 1024 / 1024 # MB
new_size = os.path.getsize(output_path) / 1024 / 1024 # MB
print(f" 文件大小: {original_size:.2f}MB -> {new_size:.2f}MB")
return True
except Exception as e:
print(f" ❌ 处理失败: {str(e)}")
return False
def process_images():
"""
批量处理original文件夹中的所有图片
"""
# 获取脚本所在目录
script_dir = Path(__file__).parent
# 设置输入输出文件夹
input_dir = script_dir / 'original'
output_dir = script_dir / 'resized'
# 检查输入文件夹是否存在
if not input_dir.exists():
print(f"❌ 错误: 找不到 '{input_dir}' 文件夹")
print(f" 请在脚本同级目录创建 'original' 文件夹并放入图片")
return
# 创建输出文件夹(如果不存在)
output_dir.mkdir(exist_ok=True)
print(f"✅ 输出文件夹: {output_dir}\n")
# 支持的图片格式
image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.tiff'}
# 获取所有图片文件
image_files = [
f for f in input_dir.iterdir()
if f.is_file() and f.suffix.lower() in image_extensions
]
if not image_files:
print(f"❌ 在 '{input_dir}' 文件夹中没有找到图片文件")
print(f" 支持的格式: {', '.join(image_extensions)}")
return
print(f"📂 找到 {len(image_files)} 个图片文件\n")
print("=" * 60)
# 处理每个图片
success_count = 0
fail_count = 0
for idx, img_path in enumerate(image_files, 1):
# 输出文件名(改为.jpg)
output_filename = img_path.stem + '.jpg'
output_path = output_dir / output_filename
print(f"\n[{idx}/{len(image_files)}] 处理: {img_path.name}")
if resize_image(img_path, output_path):
success_count += 1
print(f" ✅ 已保存: {output_filename}")
else:
fail_count += 1
# 显示总结
print("\n" + "=" * 60)
print(f"\n✨ 处理完成!")
print(f" 成功: {success_count} 个")
if fail_count > 0:
print(f" 失败: {fail_count} 个")
print(f"\n📁 所有处理后的图片保存在: {output_dir}")
if __name__ == "__main__":
print("=" * 60)
print(" 图片批量压缩工具")
print(" - 等比例缩放(最大1000px)")
print(" - 转换为JPG格式")
print(" - 质量95%")
print("=" * 60 + "\n")
try:
process_images()
except KeyboardInterrupt:
print("\n\n⚠️ 操作已取消")
except Exception as e:
print(f"\n❌ 发生错误: {str(e)}")
import traceback
traceback.print_exc()