added argparse to convert.py

This commit is contained in:
ClF3 2024-04-24 10:33:42 +08:00
parent c3680d7fda
commit 0544602000
1 changed files with 23 additions and 6 deletions

View File

@ -1,16 +1,33 @@
import os
import sys
from PIL import Image
import argparse
if __name__ == '__main__':
originalfiles = [f for f in os.listdir('original') if os.path.isfile(os.path.join('original', f))]
existingfiles = [f for f in os.listdir('webp') if os.path.isfile(os.path.join('webp', f))]
parser = argparse.ArgumentParser()
parser.add_argument('--original', help='Path to the original images', default='original')
parser.add_argument('--webp', help='Path to the webp images', default='webp')
parser.add_argument('--quality', help='Quality of the webp images', default=90, type=int)
parser.add_argument('--overwrite', help='Overwrite existing images', action='store_true')
args = parser.parse_args()
if not os.path.exists(args.original):
os.makedirs(args.original)
print("Created directory: " + args.original)
if not os.path.exists(args.webp):
os.makedirs(args.webp)
print("Created directory: " + args.webp)
originalfiles = [f for f in os.listdir(args.original) if os.path.isfile(os.path.join(args.original, f))]
existingfiles = [f for f in os.listdir(args.webp) if os.path.isfile(os.path.join(args.webp, f))]
for f in originalfiles:
if f.split(".")[0] + '.webp' in existingfiles:
if f.split(".")[0] + '.webp' in existingfiles and not args.overwrite:
print("skipped: " + f)
continue
try:
im = Image.open('original/' + f).convert('RGB')
im.save('webp/' + f.split(".")[0] + '.webp', 'WEBP', quality=90)
im = Image.open(os.path.join(args.original, f)).convert('RGB')
im.save(os.path.join(args.webp, f.split(".")[0] + '.webp'), 'WEBP', quality=args.quality)
print("optimized: " + f)
except OSError:
print("Falied to optimize the picture: " + f)
print("Falied to optimize the picture: " + f)
print("Error: ", sys.exc_info()[0])