PPaste!

jpg to png

Home - All the pastes - Authored by Thooms

Raw version

 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
from PIL import Image  # PIP install pillow

# Built-in libraries
import sys
import os
import re


def main():
    input_dir = os.path.abspath(sys.argv[1])  # 2nd Argument from command
    output_dir = os.path.abspath(sys.argv[2])  # 3rd Argument from command

    if not os.path.exists(output_dir):
        # check if the output dir doesn't exist, if so, create one
        os.mkdir(output_dir)

    if os.path.exists(input_dir):
        # loop through all files in input_dir
        for fname in os.listdir(input_dir):
            if fname.endswith('.jpg'):  # just get the files with .jpg extension
                image = Image.open(os.path.join(
                    input_dir, fname))  # Open image
                pattern = r'(.*)\.'  # set a regex pattern
                # Search for the pattern in the name of the file
                data = re.search(pattern, fname)
                # save the same name but in .png
                image.save(f'{output_dir}/{data.group(1)}.png')
    else:
        # print that the input dir doesn't exist if it actually doesn't.
        print(input_dir + 'does not exists')


if __name__ == '__main__':
    main()