blog-img-manager/convert.py

33 lines
1.5 KiB
Python

import os
import sys
from PIL import Image
import argparse
if __name__ == '__main__':
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 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])