python

#ディレクトリ内のJPEGファイルの名前を変更
#元ファイルを撮影日時でソートして、
#hina-001.jpg,hina-002.jpg,…の連番で保存
#[original_directory]の元画像ファイルは保持されます

import os
from PIL import Image, ExifTags
from datetime import datetime
import shutil  # ファイルのコピーに使用

# Exif情報から撮影日時を取得する関数
def get_image_creation_date(image_path):
    try:
        with Image.open(image_path) as img:
            exif_data = img._getexif()
            if exif_data:
                for tag, value in exif_data.items():
                    tag_name = ExifTags.TAGS.get(tag)
                    if tag_name == 'DateTimeOriginal':
                        return datetime.strptime(value, '%Y:%m:%d %H:%M:%S')
    except Exception as e:
        print(f"Error getting creation date for {image_path}: {e}")
    return None

# JPEGファイルの名前を変更してコピーして保存する
def rename_jpeg_files(original_directory, save_directory):
    jpeg_files = [file for file in os.listdir(original_directory) if file.lower().endswith('.jpg')]
    jpeg_files_with_dates = []

    # 撮影日時を取得してファイルパスとともにリストに追加する
    for filename in jpeg_files:
        file_path = os.path.join(original_directory, filename)
        creation_date = get_image_creation_date(file_path)
        if creation_date:
            jpeg_files_with_dates.append((file_path, creation_date))

    # 撮影日時でソート
    sorted_files = sorted(jpeg_files_with_dates, key=lambda x: x[1])

    # ファイルをコピーして名前を変更して保存
    for index, (old_path, _) in enumerate(sorted_files):
        new_name = f"hina-{index+1:03d}.jpg"  # ファイル名を設定
        new_path = os.path.join(save_directory, new_name)

        # ファイルをコピーして保存
        shutil.copyfile(old_path, new_path)
        print(f"Copied and renamed {old_path} to {new_path}")

# メイン関数
if __name__ == "__main__":
    original_directory = r"F:\blogger-写真20240316\hinata-baba\tmp1\resize-dir\test-in"
    save_directory = r"F:\blogger-写真20240316\hinata-baba\tmp1\resize-dir\test-out"
    rename_jpeg_files(original_directory, save_directory)