Created
May 15, 2020 02:13
-
-
Save luiscoms/eac517188e7916339ec71d3d1bc63e44 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import os | |
from os.path import splitext | |
from PIL import Image | |
DEFAULT_SIZE = (220, 180) | |
# DEFAULT_SIZE = (300, 30) | |
# DEFAULT_SIZE = (300, 128) | |
def resize_image(input_dir, infile, output_dir="resized", output_size=DEFAULT_SIZE): | |
outfile, extension = splitext(infile) | |
try: | |
img = Image.open(input_dir + '/' + infile) | |
old_size = img.size | |
img.thumbnail(output_size, Image.ANTIALIAS) # img.resize(output_size, Image.LANCZOS) | |
new_file = f"{output_dir}/{outfile}-{img.size[0]}x{img.size[0]}{extension}" | |
img.save(new_file) | |
except IOError: | |
print(f"unable to resize image {infile}") | |
else: | |
print(f"resized image {infile}, {old_size} -> {img.size}") | |
if __name__ == "__main__": | |
cur_dir = os.getcwd() | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-i', '--input_dir', help='Full Input Path') | |
parser.add_argument('-o', '--output_dir', help='Full Output Path') | |
parser.add_argument('-w', '--width', help='Resized Width') | |
parser.add_argument('-t', '--height', help='Resized Height') | |
args = parser.parse_args() | |
if args.input_dir: | |
input_dir = args.input_dir | |
else: | |
input_dir = cur_dir + '/images' | |
if args.output_dir: | |
output_dir = args.output_dir | |
else: | |
output_dir = cur_dir + '/resized' | |
if args.width and args.height: | |
output_size = (int(args.width), int(args.height)) | |
else: | |
output_size = DEFAULT_SIZE | |
if not os.path.exists(os.path.join(cur_dir, output_dir)): | |
os.mkdir(output_dir) | |
try: | |
for file in os.listdir(input_dir): | |
resize_image(input_dir, file, output_dir, output_size) | |
except OSError: | |
print('file not found') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment