From 0544602000d6d3c8d1dc213ec41a3e7234223850 Mon Sep 17 00:00:00 2001 From: ClF3 Date: Wed, 24 Apr 2024 10:33:42 +0800 Subject: [PATCH] added argparse to convert.py --- convert.py | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/convert.py b/convert.py index d8599b5..e9aba49 100644 --- a/convert.py +++ b/convert.py @@ -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) \ No newline at end of file + print("Falied to optimize the picture: " + f) + print("Error: ", sys.exc_info()[0]) \ No newline at end of file