苹果相册.heic格式转成.jpg格式

heic格式转成.jpg格式

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
import os
from PIL import Image
import pillow_heif


def convert_heic_to_jpg(input_path, output_path):
try:
heif_file = pillow_heif.read_heif(input_path)
img = Image.frombytes(
heif_file.mode,
heif_file.size,
heif_file.data,
"raw"
)

img.save(output_path, "JPEG", quality=90)
print(f"✔ HEIC 转换成功: {input_path} -> {output_path}")

except Exception as e:
print(f"✘ HEIC 转换失败: {input_path}")
print("原因:", e)


def convert_jpg_to_jpg(input_path, output_path):
try:
img = Image.open(input_path)
img.convert("RGB").save(output_path, "JPEG", quality=90)
print(f"✔ JPG 处理成功: {input_path} -> {output_path}")

except Exception as e:
print(f"✘ JPG 处理失败: {input_path}")
print("原因:", e)


def process_directory(root_folder):
for current_path, dirs, files in os.walk(root_folder):

heic_files = [f for f in files if f.lower().endswith(".heic")]
jpg_files = [f for f in files if f.lower().endswith(".jpg")]

if not heic_files and not jpg_files:
continue

is_root = os.path.abspath(current_path) == os.path.abspath(root_folder)

if is_root:
# ✅ 根目录:只处理 HEIC(避免重复处理 JPG)
for file in heic_files:
input_path = os.path.join(current_path, file)
filename = os.path.splitext(file)[0]
output_path = os.path.join(root_folder, f"{filename}.jpg")

convert_heic_to_jpg(input_path, output_path)

else:
# ✅ 子目录:HEIC 优先,没有就用 JPG
folder_name = os.path.basename(current_path)
folder_name = os.path.splitext(folder_name)[0]

output_path = os.path.join(root_folder, f"{folder_name}.jpg")

if heic_files:
input_path = os.path.join(current_path, heic_files[0])
convert_heic_to_jpg(input_path, output_path)
else:
input_path = os.path.join(current_path, jpg_files[0])
convert_jpg_to_jpg(input_path, output_path)


if __name__ == "__main__":
folder = input("请输入要转换的文件夹路径(留空 = 当前目录): ").strip()

if folder == "":
folder = "."

if not os.path.isdir(folder):
print("❌ 路径不存在:", folder)
else:
print("开始递归转换 HEIC/JPG -> JPG ...")
process_directory(folder)
print("全部完成!")