Last active
October 13, 2018 21:48
-
-
Save EhsanKia/8102b10cee8f48c22978cff9a1bfc77c to your computer and use it in GitHub Desktop.
Simple function to smartly resize an image with PIL.
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
# There are four ways a resize can go: | |
# 1. You only specify a width -> image is resized to have that width while conserving aspect ratio | |
# 2. You only specify a height -> image is resized to have that height while conserving aspect ratio | |
# 3. You specify width and height with crop off -> Image is resized to fit inside the dimensions while conserving aspect ratio | |
# 4. You specify width and height with crop on -> Image is cropped and resized to the new dimensions, centered. | |
# | |
# NOTE: This function can potentially scale up your image. | |
# You can avoid that if that's important for your use case by checking | |
# width and height against old values before resizing at the end. | |
def resize_image(img, width=None, height=None, crop=False): | |
old_width, old_height = img.size | |
current_ratio = old_width / old_height | |
if width and height: | |
if crop: | |
target_ratio = width / height | |
if target_ratio < current_ratio: | |
new_width = int(width * old_height / height) | |
x = (old_width - new_width) // 2 | |
img = img.crop((x, 0, x + new_width, old_height)) | |
elif target_ratio > current_ratio: | |
new_height = int(height * old_width / width) | |
y = (old_height - new_height) // 2 | |
img = img.crop((0, y, old_width, y + new_height)) | |
else: | |
new_width = int(height * current_ratio) | |
new_height = int(width / current_ratio) | |
if new_width > width: | |
height = new_height | |
elif new_height > height: | |
width = new_width | |
elif width: | |
height = int(width / current_ratio) | |
elif height: | |
width = int(height * current_ratio) | |
if width and height: | |
img = img.resize((width, height), Image.LANCZOS) | |
return img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment