import os from pathlib import Path from PIL import Image def batch_convert_to_ico(source_dirs, output_dir, target_size=(256, 256)): """ 批量将指定目录下的图像文件转换为 ICO 格式。 :param source_dirs: 包含源文件夹路径的列表 :param output_dir: 转换后 ICO 文件的保存目录 :param target_size: 输出 ICO 的尺寸,默认 256x256 """ # 支持的常见输入图像后缀 supported_extensions = {'.png', '.jpg', '.jpeg', '.bmp', '.webp', '.tiff'} # 确保输出目录存在,若无则自动创建 out_path = Path(output_dir) out_path.mkdir(parents=True, exist_ok=True) total_converted = 0 total_failed = 0 print("=" * 50) print(f"🚀 开始批量转换 ICO 图标...") print(f"📁 目标输出目录: {out_path}") print("=" * 50) # 遍历所有传入的源目录 for folder in source_dirs: folder_path = Path(folder) if not folder_path.exists(): print(f"⚠️ 警告: 源目录不存在,已跳过 -> {folder_path}") continue print(f"\n📂 正在扫描目录: {folder_path}") # 遍历目录下的所有文件 for file_path in folder_path.iterdir(): # 仅处理普通文件且后缀在支持列表内(忽略大小写) if file_path.is_file() and file_path.suffix.lower() in supported_extensions: try: with Image.open(file_path) as img: # 处理透明通道问题: # 如果图片支持透明通道 (RGBA/P/LA),转为 RGBA 确保透明背景不丢失 # 如果是普通 RGB (如 JPG),转为 RGB if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info): img_clean = img.convert('RGBA') else: img_clean = img.convert('RGB') # 构造输出文件名 (原文件名.ico) new_filename = f"{file_path.stem}.ico" save_path = out_path / new_filename # 如果目标文件夹中已存在同名文件,为了防止覆盖,可以在文件名后加个标识 # 但通常图标库同名直接覆盖较符合需求,这里默认直接保存 img_clean.save(save_path, format="ICO", sizes=[target_size]) print(f" ✅ 成功: {file_path.name} -> {new_filename}") total_converted += 1 except Exception as e: print(f" ❌ 失败: 无法转换 {file_path.name},错误信息: {e}") total_failed += 1 print("\n" + "=" * 50) print("🎉 转换任务结束!") print(f"统计: 成功转换 {total_converted} 个文件,失败 {total_failed} 个。") print("=" * 50) if __name__ == "__main__": # 1. 定义你要读取的两个源文件夹路径列表 SOURCES = [ r"D:\111\office\ZHLduijie\1.WQ\WQ_GUI\data\icons", r"D:\111\office\ZHLduijie\1.WQ\WQ_GUI\data\icons\word" ] # 2. 定义统一输出的目标文件夹路径 OUTPUT = r"D:\111\office\ZHLduijie\1.WQ\WQ_GUI\data\icons-1" # 执行转换 batch_convert_to_ico(SOURCES, OUTPUT)