Last active
December 25, 2015 11:59
-
-
Save flyte/6973496 to your computer and use it in GitHub Desktop.
Resize an image to multiple different sizes based on their long edge size.
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
from PIL import Image | |
import os | |
import argparse | |
p = argparse.ArgumentParser() | |
p.add_argument("img_filename") | |
sizes = { | |
"thumbnail": 100, | |
"small": 240, | |
"small 320": 320, | |
"medium": 500, | |
"medium 640": 640, | |
"medium 800": 800, | |
"large": 1024, | |
"large 1600": 1600, | |
"large 2048": 2048 | |
} | |
def new_size(long_edge_px, current_dimensions): | |
cx, cy = current_dimensions | |
if cx >= cy: | |
ratio = float(cx)/float(cy) | |
return (long_edge_px, int(long_edge_px/ratio)) | |
else: | |
ratio = float(cy)/float(cx) | |
return (int(long_edge_px/ratio), long_edge_px) | |
def resize_and_save(filename, long_edge_px, new_filename): | |
print "Resizing %s to %spx and saving as %s" % ( | |
filename, long_edge_px, new_filename) | |
img = Image.open(filename) | |
img.resize(new_size(long_edge_px, img.size), Image.ANTIALIAS).save(new_filename) | |
if __name__ == "__main__": | |
args = p.parse_args() | |
for size_name, size in sizes.items(): | |
filename, ext = os.path.splitext(args.img_filename) | |
resize_and_save(args.img_filename, size, "%s_%s%s" % ( | |
filename, size_name, ext)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment