Skip to content

Instantly share code, notes, and snippets.

@comtom
Created February 29, 2020 22:35
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 comtom/d56051987189aa61041442c7d504a42d to your computer and use it in GitHub Desktop.
Save comtom/d56051987189aa61041442c7d504a42d to your computer and use it in GitHub Desktop.
from PIL import Image
def resize_and_crop(img, size=(255, 255)):
img = Image.open(img)
img_ratio = img.size[0] / img.size[1]
ratio = size[0] / size[1]
if ratio > img_ratio:
img = img.resize((size[0], int(size[0] * img.size[1] / img.size[0])),
Image.ANTIALIAS)
box = (0, (img.size[1] - size[1]) / 2, img.size[0],
(img.size[1] + size[1]) / 2)
img = img.crop(box)
elif ratio < img_ratio:
img = img.resize((int(size[1] * img.size[0] / img.size[1]), size[1]),
Image.ANTIALIAS)
box = ((img.size[0] - size[0]) / 2, 0, (img.size[0] + size[0]) / 2,
img.size[1])
img = img.crop(box)
else:
# no cropping necessary
img = img.resize((size[0], size[1]), Image.ANTIALIAS)
# save thumbnail
img.save('./thumb.jpg')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment