套件:https://pypi.org/project/pillow-heif/
安裝套件:
pip install pillow-heif
程式碼是用ChatGPT產生,提示語如下:
Python程式,針對一個目錄,底下有子目錄也有HEIC檔案和其他檔案,請把HEIC 轉JPG 轉換
但產生出來的程式不能用,後改用第二提示語:
請用pillow_heif
以下程式經測試是可以的。
程式碼:
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 | import os from PIL import Image import pillow_heif def convert_heic_to_jpg(input_path, output_path): heif_file = pillow_heif.open_heif(input_path) image = Image.frombytes( heif_file.mode, heif_file.size, heif_file.data, "raw", heif_file.mode, heif_file.stride, ) image.save(output_path, "JPEG") def process_directory(directory): for root, _, files in os.walk(directory): for file in files: if file.lower().endswith('.heic'): input_file = os.path.join(root, file) output_file = os.path.splitext(input_file)[0] + '.jpg' try: convert_heic_to_jpg(input_file, output_file) print(f"Converted: {input_file} -> {output_file}") except Exception as e: print(f"Failed to convert {input_file}: {e}") if __name__ == "__main__": directory = input("Enter the directory path: ") process_directory(directory) |
執行結果:
Enter the directory path: Apple
Converted: Apple\sample1.heic -> Apple\sample1.jpg
Converted: Apple\APPLE01\sample1.heic -> Apple\APPLE01\sample1.jpg
查看目錄:
沒有留言:
張貼留言