Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Resize a folder of images to a set max width / height dimension, keeping proportions constrained
import click
import glob
import os
from PIL import Image
help='The max height / width of image in pixels.'
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:')
output_folder = '{}-{}px'.format(images_folder, max_px_size)
if not os.path.exists(output_folder):
for img_path in imgs:
resize(img_path, max_px_size, output_folder)
except Exception as e:
with open('error.txt', 'w') as f:
def resize(img_path, max_px_size, output_folder):
with 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))
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))
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))
if __name__ == '__main__':

This comment has been minimized.

Copy link
Owner Author

commented May 31, 2018

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.

python --max-px-size 4000 --images-folder my_SLR_pictures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.