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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| import os from PIL import Image
def get_resolution_input(prompt): """获取用户输入的分辨率,格式为'宽 高'""" while True: try: res_input = input(prompt).strip() width, height = map(int, res_input.split()) if width <= 0 or height <= 0: print("分辨率必须为正整数,请重新输入") continue return width, height except ValueError: print("输入格式错误,请按'宽 高'格式输入(例如:480 640)")
def needs_resize(img, max_width, max_height): """检查图片是否需要调整大小""" return img.width > max_width or img.height > max_height
def process_images(input_folder, output_folder, max_width, max_height, copy_untouched): """处理图片主函数""" os.makedirs(output_folder, exist_ok=True) failed_files = [] processed_count = 0 copied_count = 0 skipped_count = 0
for root, _, files in os.walk(input_folder): for file in files: if not file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp')): continue input_path = os.path.join(root, file) rel_path = os.path.relpath(root, input_folder) output_dir = os.path.join(output_folder, rel_path) output_path = os.path.join(output_dir, file) try: with Image.open(input_path) as img: if needs_resize(img, max_width, max_height): ratio = min(max_width / img.width, max_height / img.height) new_size = (int(img.width * ratio), int(img.height * ratio)) resized_img = img.resize(new_size, Image.LANCZOS) os.makedirs(output_dir, exist_ok=True) resized_img.save(output_path) processed_count += 1 print(f"[处理] {input_path} -> {output_path}") elif copy_untouched: os.makedirs(output_dir, exist_ok=True) img.save(output_path) copied_count += 1 print(f"[复制] {input_path} -> {output_path}") else: skipped_count += 1 print(f"[跳过] {input_path} (无需调整)") except Exception as e: failed_files.append(input_path) print(f"[失败] {input_path} - 错误: {str(e)}") print("\n=== 处理结果 ===") print(f"目标分辨率: {max_width}×{max_height}") print(f"已处理图片数量: {processed_count}") if copy_untouched: print(f"已复制未处理图片数量: {copied_count}") print(f"跳过图片数量: {skipped_count}") print(f"失败图片数量: {len(failed_files)}") if failed_files: print("\n=== 处理失败的图片 ===") for i, file in enumerate(failed_files, 1): print(f"{i}. {file}")
if __name__ == "__main__": print("=== 图片批量处理工具 ===") print("功能说明:") print("1. 将大于指定分辨率的图片调整为不超过该尺寸") print("2. 可选择是否复制未处理的照片到新文件夹") print("3. 保持原始目录结构\n") input_folder = input("请输入源文件夹路径: ").strip() output_folder = input("请输入目标文件夹路径: ").strip() max_width, max_height = get_resolution_input("请输入目标分辨率(格式: 宽 高,例如480 640): ") copy_choice = input("是否需要将未处理的照片一并复制到新文件夹? (y/n): ").strip().lower() if not os.path.exists(input_folder): print("错误: 源文件夹不存在!") else: try: process_images( input_folder=input_folder, output_folder=output_folder, max_width=max_width, max_height=max_height, copy_untouched=copy_choice == 'y' ) except KeyboardInterrupt: print("\n操作已取消") except Exception as e: print(f"发生错误: {str(e)}") finally: input("\n按Enter键退出...")
|