Created
December 9, 2011 05:48
-
-
Save yosemitebandit/1450365 to your computer and use it in GitHub Desktop.
makes thumbnails
This file contains hidden or 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
#!/usr/bin/env python | |
''' | |
thumb.py | |
making little images; PIL's thumbnail method be damned! | |
usage: | |
$ thumb target.png | |
$ thumb target.png -W 300 | |
$ thumb target.jpg -W 300 -H 200 | |
$ thumb target.jpg -W 300 -H 200 -o /thumbs/target_thumb.png | |
''' | |
import optparse | |
import os | |
import sys | |
import Image | |
parser = optparse.OptionParser() | |
parser.add_option('-W', '--width', help='width in pixels', dest='width') | |
parser.add_option('-H', '--height', help='height in pixels', dest='height') | |
parser.add_option('-o', '--output', help='output file path', dest='save_path') | |
(opts, args) = parser.parse_args() | |
original_path = sys.argv[1] # didn't want this behind optparse | |
original = Image.open(original_path) | |
aspect_ratio = original.size[0]/float(original.size[1]) | |
# find the widths and heights | |
if not opts.width and not opts.height: | |
width = 200 | |
height = width/aspect_ratio | |
print 'fixing width at 200px and holding aspect ratio' | |
elif not opts.width: | |
width = int(opts.height)*aspect_ratio | |
height = opts.height | |
print 'holding aspect ratio' | |
elif not opts.height: | |
width = opts.width | |
height = int(opts.width)/aspect_ratio | |
print 'holding aspect ratio' | |
else: | |
width = opts.width | |
height = opts.height | |
# append thumb and save it where it stands; break down for clarity | |
if not opts.save_path: | |
original_name, original_extension = os.path.splitext(original_path) | |
save_path = '%s-thumb%s' % (original_name, original_extension) | |
else: | |
save_path = opts.save_path | |
# resize and save | |
thumb = original.resize((int(width), int(height)), Image.ANTIALIAS) | |
thumb.save(save_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment