图片镜像程序(输入父目录与阈值)

发布时间 2023-12-22 11:32:11作者: 不上火星不改名
import os
from PIL import Image

def mirror_images_in_subfolders(parent_directory, x_threshold):
    """
    遍历指定目录,找到包含图片数量少于指定阈值的子文件夹,并镜像这些图片,
    同时保存新名称以避免重复。
    :param parent_directory: 要搜索的根目录。
    :param x_threshold: 文件夹被考虑进行镜像的最大图片数量。
    :return: None
    """
    # 在父目录中遍历所有目录和文件
    for subdir, dirs, files in os.walk(parent_directory):
        image_files = [file for file in files if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]
        image_count = len(image_files)

        # 检查图片数量是否少于阈值且大于0
        if 0 < image_count < x_threshold:
            print(f"正在镜像以下文件夹中的图片: {subdir} - 图片总数: {image_count}")

            # 处理每个图片文件
            for image_file in image_files:
                try:
                    # 构建完整的文件路径
                    file_path = os.path.join(subdir, image_file)
                    # 打开并镜像图片
                    with Image.open(file_path) as img:
                        mirrored_img = img.transpose(Image.FLIP_LEFT_RIGHT)

                        # 分离文件名和扩展名
                        name, extension = os.path.splitext(image_file)
                        # 创建带有(1)后缀的新名称
                        new_name = f"{name}(1){extension}"
                        new_path = os.path.join(subdir, new_name)

                        # 检查新文件名是否存在,避免覆盖
                        if not os.path.exists(new_path):
                            # 将镜像后的图片保存回同一目录并使用新名称
                            mirrored_img.save(new_path)
                        else:
                            print(f"警告: 文件 {new_path} 已存在,跳过此文件。")
                except Exception as e:
                    print(f"处理图片 {image_file} 时发生错误: {e}")

            print(f"完成镜像以下文件夹中的图片: {subdir}")

if __name__ == "__main__":
    # 提示用户输入父目录和X阈值
    parent_dir = input("请输入父目录的地址: ")
    x_value = int(input("请输入X值(图片数量阈值): "))

    # 执行镜像过程
    mirror_images_in_subfolders(parent_dir, x_value)