Skip to content

Instantly share code, notes, and snippets.

@Saigesp
Last active December 4, 2020 15:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Saigesp/111cc103a837344f4fcda2a2d2090c66 to your computer and use it in GitHub Desktop.
Save Saigesp/111cc103a837344f4fcda2a2d2090c66 to your computer and use it in GitHub Desktop.
Python script to resize images, with command line arguments. Adapted from https://gist.github.com/ihercowitz/642650/f01986c0b1ebd04be588b196eb3ffefe9853e113
#!/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 image_resize.py -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")):
return
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(size, Image.ANTIALIAS)
im.save(os.path.join(output_dir, 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):
os.mkdir(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