Created
February 22, 2014 00:23
-
-
Save abelsonlive/9146555 to your computer and use it in GitHub Desktop.
resize images intelligently
This file contains 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 | |
def smart_resize(filepath = "samp.png", width = 612, height = 612): | |
img = Image.open(image_file) | |
orig_height, orig_width = img.size | |
if orig_height >= orig_width: | |
f = float(width) / float(orig_width) | |
else: | |
f = float(height) / float(orig_height) | |
new_img = img.resize((int(orig_height*f), int(orig_width*f)), Image.ANTIALIAS) | |
new_height, new_width = new_img.size | |
width_delta = (new_width - width)/2 | |
height_delta = (new_height - height)/2 | |
dim = ( | |
0 + height_delta, | |
0 + width_delta, | |
new_height - height_delta, | |
new_width - width_delta | |
) | |
final_img = new_img.crop(dim) | |
final_img.save('reisze-%' % filepath) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment