Created
May 22, 2014 19:13
-
-
Save pbdeuchler/576daa6d126ec99d545d to your computer and use it in GitHub Desktop.
Adaptive resize for avatars using Python and PIL/Pillow, square crop from center plus an optional resizing
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
def adaptive_resize(img, size=None): #img is a PIL/Pillow Image object, size is a tuple of desired dimensions | |
if size is not None: # resize image | |
if size[0] != size[1]: | |
raise Exception("Provided target dimensions must be equal") | |
smallest_side = min(img.size[0], img.size[1]) | |
if size[0] < smallest_side: # make sure we actually need to resize | |
resize_ratio = float(size[0]) / float(smallest_side) | |
resize_x = int(math.floor(img.size[0] * resize_ratio)) | |
resize_y = int(math.floor(img.size[1] * resize_ratio)) | |
img = img.resize((resize_x, resize_y)) | |
if img.size[0] < img.size[1]: # if y is greater than x | |
top, bottom = crop_dimensions_math(img.size) | |
crop_dimensions = (0, img.size[1] - top, img.size[0], img.size[1] - bottom) # coordinates are measured from the top boundry | |
elif img.size[0] > img.size[1]: # if x is greater than y | |
left, right = crop_dimensions_math(img.size) | |
crop_dimensions = (img.size[0] - left, 0, img.size[0] - right, img.size[1]) # coordinates are measured from the left boundry | |
else: # image is already a square, no need for cropping | |
crop_dimensions = None | |
if crop_dimensions is not None: # crop (if neccessary) | |
img = img.crop(crop_dimensions) | |
return img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
function crop_dimensions_math ?