blog-img-manager/convert.py

35 lines
1.6 KiB
Python
Raw Normal View History

2024-04-20 02:14:37 +00:00
import os
import sys
from PIL import Image
2024-04-24 02:33:42 +00:00
import argparse
2024-04-27 07:29:59 +00:00
import json
2024-04-20 02:14:37 +00:00
if __name__ == '__main__':
2024-04-27 07:29:59 +00:00
defaults=json.load(open('defaults.json'))
2024-04-24 02:33:42 +00:00
parser = argparse.ArgumentParser()
2024-04-27 07:29:59 +00:00
parser.add_argument('--original', help='Path to the original images', default=defaults['original'])
parser.add_argument('--webp', help='Path to the webp images', default=defaults['webp'])
parser.add_argument('--quality', help='Quality of the webp images', default=defaults['quality'], type=int)
2024-04-24 02:33:42 +00:00
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))]
2024-04-24 03:01:26 +00:00
2024-04-20 02:14:37 +00:00
for f in originalfiles:
2024-04-24 02:33:42 +00:00
if f.split(".")[0] + '.webp' in existingfiles and not args.overwrite:
2024-04-20 02:14:37 +00:00
print("skipped: " + f)
continue
try:
2024-04-24 02:33:42 +00:00
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)
2024-04-20 02:14:37 +00:00
print("optimized: " + f)
except OSError:
2024-04-24 02:33:42 +00:00
print("Falied to optimize the picture: " + f)
print("Error: ", sys.exc_info()[0])