Skip to content

Instantly share code, notes, and snippets.

@pbdeuchler
Created May 22, 2014 19:13
Show Gist options
  • Save pbdeuchler/576daa6d126ec99d545d to your computer and use it in GitHub Desktop.
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
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
@ZephiroRB
Copy link

function crop_dimensions_math ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment