-
Notifications
You must be signed in to change notification settings - Fork 0
/
real_pic_suffix
57 lines (49 loc) · 2.29 KB
/
real_pic_suffix
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
import os
from PIL import Image
import io
# 需要的依赖
# pip install pillow
# 设定支持的图片格式
SUPPORTED_FORMATS = {
"JPEG": "jpg",
"PNG": "png",
"WEBP": "webp"
}
def is_image_file(filename):
# 只处理设定的图片格式
valid_extensions = {"jpg", "jpeg", "png", "webp"}
return filename.split(".")[-1].lower() in valid_extensions
def check_image_format_and_extension(root_dir):
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
if not is_image_file(filename):
# 跳过非图片文件
continue
file_path = os.path.join(dirpath, filename)
file_extension = filename.split(".")[-1].lower()
try:
# 读取文件并加载到内存中来检测图片格式,不然一会儿改名时文件会被占用
with open(file_path, "rb") as file:
image_data = io.BytesIO(file.read())
with Image.open(image_data) as img:
actual_format = img.format
if actual_format in SUPPORTED_FORMATS:
actual_extension = SUPPORTED_FORMATS[actual_format]
if actual_extension != file_extension:
# 使用临时文件名.temp来避免重命名冲突
temp_file_path = file_path + ".temp"
os.rename(file_path, temp_file_path)
correct_file_path = temp_file_path.rsplit(".", 2)[0] + "." + actual_extension
os.rename(temp_file_path, correct_file_path)
print(f"已将文件 {file_path} 重命名为 {correct_file_path}")
else:
print(f"文件 {file_path} 的格式与后缀名匹配")
else:
print(f"文件 {file_path} 的格式 {actual_format} 不支持")
except Exception as e:
print(f"处理文件 {file_path} 时出错: {e}")
if __name__ == "__main__":
# 获取当前.py文件所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
print(f"正在检查文件夹: {current_dir}")
check_image_format_and_extension(current_dir)