File size: 1,196 Bytes
d67c45e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)