Skip to content

Instantly share code, notes, and snippets.

@redutan
Last active July 21, 2016 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redutan/0f509a37434fdfac8490b92e027fe488 to your computer and use it in GitHub Desktop.
Save redutan/0f509a37434fdfac8490b92e027fe488 to your computer and use it in GitHub Desktop.
Resize all images in a folder based on the width
#!/usr/bin/python
# usage python resizeimgs.py PATH WIDTH
import sys
from os import listdir, path
from PIL import Image
def getpath():
try:
inpath = sys.argv[1]
except:
raise Error("please input PATH : python resizeimgs.py PATH WIDTH")
return inpath
def getwidth():
try:
inwidth = sys.argv[2]
except:
raise Error("please input WIDTH : python resizeimgs.py PATH WIDTH")
return int(inwidth)
def getfiles(dir):
return [path.join(dir, f) for f in listdir(dir) if path.isfile(path.join(dir, f))]
def resizeimgs(files, width):
for f in files:
try:
img = Image.open(f)
except IOError:
continue
fname, ext = path.splitext(f);
outfile = fname + "." + str(width) + ext
# resize
img.thumbnail((width, width), Image.ANTIALIAS)
img.save(outfile)
print("resized : " + outfile)
files = getfiles(getpath())
width = getwidth()
resizeimgs(files, width)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment