-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreal_pic_suffix
More file actions
85 lines (69 loc) · 2.92 KB
/
real_pic_suffix
File metadata and controls
85 lines (69 loc) · 2.92 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
import os
from PIL import Image
import io
from concurrent.futures import ThreadPoolExecutor
import logging
# 需要安装的依赖
# pip install pillow pillow-heif pillow-avif-plugin
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# 扩展支持的图片格式(格式名 -> 标准后缀)
SUPPORTED_FORMATS = {
"JPEG": "jpg",
"PNG": "png",
"WEBP": "webp",
"GIF": "gif",
"BMP": "bmp",
"TIFF": "tiff",
"HEIC": "heic",
"AVIF": "avif"
}
# 支持的扩展名(小写)
VALID_EXTENSIONS = {v.lower() for v in SUPPORTED_FORMATS.values()} | {"jpeg", "tif"}
def is_image_file(filename):
return filename.split(".")[-1].lower() in VALID_EXTENSIONS
def process_file(file_path):
try:
filename = os.path.basename(file_path)
file_extension = filename.split(".")[-1].lower()
# 读取文件到内存
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 not in SUPPORTED_FORMATS:
logging.warning(f"文件 {file_path} 的格式 {actual_format} 不支持")
return
correct_extension = SUPPORTED_FORMATS[actual_format]
if correct_extension == file_extension:
logging.info(f"格式匹配: {file_path}")
return
# 重命名文件为真实格式
base_name = os.path.splitext(filename)[0]
new_filename = f"{base_name}.{correct_extension}"
new_path = os.path.join(os.path.dirname(file_path), new_filename)
# 文件名冲突解决
counter = 1
while os.path.exists(new_path):
new_filename = f"{base_name}_{counter}.{correct_extension}"
new_path = os.path.join(os.path.dirname(file_path), new_filename)
counter += 1
os.rename(file_path, new_path)
logging.info(f"重命名成功: {file_path} -> {new_path}")
except Exception as e:
logging.error(f"处理文件 {file_path} 失败: {str(e)}", exc_info=True)
def check_image_format_and_extension(root_dir):
file_paths = []
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_paths.append(file_path)
# 并行处理提高速度
with ThreadPoolExecutor(max_workers=os.cpu_count() * 2) as executor:
executor.map(process_file, file_paths)
if __name__ == "__main__":
current_dir = os.path.dirname(os.path.abspath(__file__))
logging.info(f"开始检查目录: {current_dir}")
check_image_format_and_extension(current_dir)