#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import getopt from PIL import Image from resizeimage import resizeimage def compressor(file, final_path, quality, resize, size): # get filepath of image filepath = os.path.join(os.getcwd(), file) # open image with Image.open(filepath) as image: cover = image # resize if resize: print('resizing:' + file) if cover.width >= size and cover.width >= cover.height: cover = resizeimage.resize_width(cover, size) elif cover.height >= size and cover.height >= cover.width: cover = resizeimage.resize_height(cover, size) # convert to 8 bit (if possible) print('converting to 8 bit: ' + file) if cover.format in ['JPG', 'JPEG']: # TODO: JPG + JPEG are not converted to 8 bit cover = cover.quantize(colors=256, method=2).convert("RGB") else: cover = cover.quantize(colors=256, method=2) # compress and save print('compressing: ' + file) cover.save( str(final_path) + '/' + 'min-' + file, image.format, optimize=True, quality=quality, ) def convert_to_webp(file, final_path): filepath = os.path.join(final_path, file) with Image.open(filepath) as image: print('converting to webp: ' + file) image.save( str(final_path) + '/' + os.path.splitext(file)[0] + '.webp', format="WEBP" ) def usage(): print(f'Usage: {os.path.basename(__file__)} [-h|--help] [-r|--resize] [-q|--quality QUALITY] [-s|--size SIZE]') print('Compress and optionally resize all images (jpg|jpeg|png|webp|gif) in the current folder') print(' -h | --help Prints this help') print(' -r | --resize Set this to resize the images') print(' -c | --convert Set this to convert images to WEBP') print(' -q | --quality QUALITY Specify the quality (1-100, default 80)') print(' -s | --size SIZE Specify the size of the long side (default 900)') def main(argv): # save arguments and options to variables try: opts, args = getopt.getopt(argv, 'hrcq:s:', ['help', 'resize', 'convert', 'quality=', 'size=']) except getopt.GetoptError as err: print(err) usage() sys.exit(2) # default values quality_img = 80 resize = False convert = False size = 900 # parse arguments for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() elif o in ('-r', '--resize'): resize = True elif o in ('-c', '--convert'): convert = True elif o in ('-q', '--quality'): quality_img = int(a) elif o in ('-s', '--size'): size = int(a) else: assert False, 'unhandled option' # save directory name directory_name = 'compress' # save directory name and full path final_path = f"{os.getcwd()}/{directory_name}" try: # if save directory exists if directory_name in os.listdir(): pass else: # if save directory does not exist # create save directory os.mkdir(final_path) except Exception as e: print(e) # get all files for file in os.listdir(os.getcwd()): # check file and compress file if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg', '.png', '.webp', '.gif'): # call compress function compressor(file, final_path, quality_img, resize, size) # convert to webp if convert: for file in os.listdir(final_path): if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg', '.png', '.gif'): convert_to_webp(file, final_path) print("Done") # Driver code if __name__ == "__main__": main(sys.argv[1:])