| import argparse | |
| from PIL import Image | |
| import json | |
| import os | |
| def process_images(image_filenames): | |
| for image_filename in image_filenames: | |
| prefix = os.path.splitext(image_filename)[0] | |
| converted = False | |
| if os.path.isfile(image_filename): | |
| # 打开图片 | |
| try: | |
| with Image.open(image_filename) as img: | |
| if(img.format != 'PNG'): | |
| img.save(f"{prefix}.png","PNG") | |
| converted=True | |
| print(f"convert {image_filename} to png") | |
| except (IOError, SyntaxError) as e: | |
| print(e) | |
| if(converted): os.remove(image_filename) | |
| else: | |
| print(f"文件 {image_filename} 不存在。") | |
| if __name__ == "__main__": | |
| # 创建命令行解析器 | |
| parser = argparse.ArgumentParser(description='读取图片文件并输出为 JSON 格式') | |
| # 添加位置参数,接受多个图片文件名 | |
| parser.add_argument('image_filenames', nargs='+', help='要处理的图片文件名') | |
| # 解析命令行参数 | |
| args = parser.parse_args() | |
| # 调用主函数 | |
| process_images(args.image_filenames) | |