Skip to content

Instantly share code, notes, and snippets.

@abelsonlive
Created February 22, 2014 00:23
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 abelsonlive/9146555 to your computer and use it in GitHub Desktop.
Save abelsonlive/9146555 to your computer and use it in GitHub Desktop.
resize images intelligently
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