import os
from PIL import Image
import pillow_heif # 輕量級HEIC處理庫
def convert_heic_to_jpg(input_folder, output_folder):
"""將HEIC文件轉(zhuǎn)換為JPG,保存到指定文件夾"""
# 初始化pillow-heif
pillow_heif.register_heif_opener() # 注冊HEIC格式支持
# 處理路徑
input_folder = input_folder.strip()
output_folder = output_folder.strip()
# 檢查輸入文件夾
if not os.path.exists(input_folder):
print(f"錯誤:輸入文件夾 '{input_folder}' 不存在")
return
# 創(chuàng)建輸出文件夾
os.makedirs(output_folder, exist_ok=True)
converted_count = 0
skipped_count = 0
# 遍歷文件
for filename in os.listdir(input_folder):
if filename.lower().endswith(('.heic', '.heif')):
heic_path = os.path.join(input_folder, filename)
jpg_filename = os.path.splitext(filename)[0] + '.jpg'
jpg_path = os.path.join(output_folder, jpg_filename)
# 跳過已存在的JPG
if os.path.exists(jpg_path):
print(f"已跳過:{filename}(JPG已存在)")
skipped_count += 1
continue
try:
# 用Pillow直接打開HEIC(因為注冊了opener)
with Image.open(heic_path) as img:
# 保存為JPG(質(zhì)量95)
img.save(jpg_path, "JPEG", quality=95)
print(f"已轉(zhuǎn)換:{filename} -> 保存至 {output_folder}")
converted_count += 1
except Exception as e:
print(f"轉(zhuǎn)換失敗:{filename} - 錯誤:{str(e)}")
print("\n轉(zhuǎn)換完成!")
print(f"成功轉(zhuǎn)換:{converted_count} 個文件")
print(f"已跳過:{skipped_count} 個文件")
if __name__ == "__main__":
# 輸入文件夾(HEIC所在路徑)
input_folder = r"D:\test1\hec" # 直接粘貼路徑
# 輸出文件夾(JPG保存路徑)
output_folder = r"D:\test1\jpg_output" # 自定義路徑
convert_heic_to_jpg(input_folder, output_folder)