blog-img-manager/convert.py

35 lines
1.6 KiB
Python

import os
import sys
from PIL import Image
import argparse
import json
if __name__ == '__main__':
defaults=json.load(open('defaults.json'))
parser = argparse.ArgumentParser()
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)
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 and not args.overwrite:
print("skipped: " + f)
continue
try:
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("Error: ", sys.exc_info()[0])