Skip to content

Instantly share code, notes, and snippets.



Last active Dec 4, 2020
What would you like to do?
Python script to resize images, with command line arguments. Adapted from
#!/usr/bin/env python
import os
import sys
import argparse
from PIL import Image
Reduce images size
Images are resized keeping the aspect ratio
Usage: python -d /home/images -o /home/output_dir -s 1024 768
def resizeImage(infile, output_dir, size):
outfile = os.path.splitext(os.path.basename(infile))[0]
extension = os.path.splitext(infile)[1]
if (cmp(extension, ".jpg")):
if infile != outfile:
im =
im.thumbnail(size, Image.ANTIALIAS), outfile+extension),"JPEG")
except IOError:
print "cannot reduce image for ", infile
if __name__=="__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-d", help="Directory to look up for images")
parser.add_argument("-o", help="Output directory")
parser.add_argument("-s", nargs=2, type=int, help="Output size")
args = parser.parse_args()
input_dir = os.path.normpath(args.d) if args.d else os.getcwd()
output_dir = os.path.normpath(args.o) if args.o else os.path.join(os.getcwd(), 'resized')
output_size = tuple(args.s) if args.s else (1024,768)
if not os.path.exists(output_dir):
for file in os.listdir(input_dir):
resizeImage(os.path.join(input_dir, file), output_dir, output_size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment