changed usage from userinput to arguments and options

This commit is contained in:
2022-01-26 13:28:32 +01:00
parent a4098b05c2
commit 2c8dbe2718

View File

@@ -1,32 +1,14 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import sys
import sys
import os
import getopt
from PIL import Image
from resizeimage import resizeimage
# save directory name
directory_name = 'compress'
# save directory name and full path
final_path = f"{os.getcwd()}/{directory_name}"
try:
# if save directory is exists
if 'compress' in os.listdir():
pass
else:
# save directory not exist
# create save directory
os.mkdir(final_path)
except Exception as e:
print(e)
def compressor(file, quality, resize, size):
def compressor(file, final_path, quality, resize, size):
# get filepath of image
filepath = os.path.join(os.getcwd(), file)
@@ -68,35 +50,75 @@ def compressor(file, quality, resize, size):
)
def main(quality_img, resize, size):
# get current directory path
cwd = os.getcwd()
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) in the current folder')
print(' -h | --help Prints this help')
print(' -r | --resize Set this to resize the images')
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, 'hrq:s:', ['help', 'resize', 'quality=', 'size='])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
# default values
quality_img = 80
resize = False
size = 900
# parse arguments
for o, a in opts:
if o in ('-h', '--help'):
usage()
sys.exit()
elif o in ('-r', '--resize'):
print(o)
resize = True
elif o in ('-q', '--quality'):
print(o, a)
quality_img = int(a)
elif o in ('-s', '--size'):
print(o, a)
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 'compress' in os.listdir():
pass
else:
# if save directory does not exist
# create save directory
os.mkdir(final_path)
except Exception as e:
print(e)
# only support these 4 formats
formats = ('.jpg', '.jpeg', '.png', '.webp')
# get all files
for file in os.listdir(cwd):
for file in os.listdir(os.getcwd()):
# check file and compress file
if os.path.splitext(file)[1].lower() in formats:
# call compress function
compressor(file, quality_img, resize, size)
compressor(file, final_path, quality_img, resize, size)
print("Done")
# Driver code
if __name__ == "__main__":
size = 900
# get image quality from user
quality_img = int(input("Enter image quality 1 to 100 (defaults to 80): ") or "80")
# check for resize
resize = str(input("Resize images? (N/y): ") or "N").lower()
if resize == 'n':
resize = False
elif resize == 'y':
resize = True
# get desired size
size = int(input("Size of longer side (defaults to 900): ") or "900")
main(quality_img, resize, size)
main(sys.argv[1:])