Last active
October 19, 2019 11:58
-
-
Save agalea91/12149be6d4f64ba61c7b1d222fce3174 to your computer and use it in GitHub Desktop.
Resize a folder of images to a set max width / height dimension, keeping proportions constrained
This file contains 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 click | |
import glob | |
import os | |
from PIL import Image | |
@click.command() | |
@click.option( | |
'--max-px-size', | |
default=2560, | |
help='The max height / width of image in pixels.' | |
) | |
@click.option( | |
'--images-folder', | |
default='images', | |
help='Name of folder containing images.' | |
) | |
def main(max_px_size, images_folder): | |
imgs = [] | |
imgs += sorted(glob.glob(os.path.join(images_folder, '*.jpg'))) | |
imgs += sorted(glob.glob(os.path.join(images_folder, '*.jpeg'))) | |
print('Image files to resize:') | |
print('\n'.join(imgs)) | |
output_folder = '{}-{}px'.format(images_folder, max_px_size) | |
if not os.path.exists(output_folder): | |
os.makedirs(output_folder) | |
for img_path in imgs: | |
try: | |
resize(img_path, max_px_size, output_folder) | |
except Exception as e: | |
with open('error.txt', 'w') as f: | |
f.write(str(e)) | |
def resize(img_path, max_px_size, output_folder): | |
with Image.open(img_path) as img: | |
width_0, height_0 = img.size | |
out_f_name = os.path.split(img_path)[-1] | |
out_f_path = os.path.join(output_folder, out_f_name) | |
if max((width_0, height_0)) <= max_px_size: | |
print('writing {} to disk (no change from original)'.format(out_f_path)) | |
img.save(out_f_path) | |
return | |
if width_0 > height_0: | |
wpercent = max_px_size / float(width_0) | |
hsize = int(float(height_0) * float(wpercent)) | |
img = img.resize((max_px_size, hsize), Image.ANTIALIAS) | |
print('writing {} to disk'.format(out_f_path)) | |
img.save(out_f_path) | |
return | |
if width_0 < height_0: | |
hpercent = max_px_size / float(height_0) | |
wsize = int(float(width_0) * float(hpercent)) | |
img = img.resize((wsize, max_px_size), Image.ANTIALIAS) | |
print('writing {} to disk'.format(out_f_path)) | |
img.save(out_f_path) | |
return | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script should be placed outside the images folder. By default this folder should be named
images
. The default max dimension size is 2560px, but it can be specified manually using the CLI e.g.