Created
February 29, 2020 22:35
-
-
Save comtom/d56051987189aa61041442c7d504a42d to your computer and use it in GitHub Desktop.
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
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