Last active
June 28, 2022 19:20
-
-
Save BIGBALLON/cb6ab73f6aaaa068ab6756611bb324b2 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, ImageOps | |
def padding(img, expected_size): | |
desired_size = expected_size | |
delta_width = desired_size - img.size[0] | |
delta_height = desired_size - img.size[1] | |
pad_width = delta_width // 2 | |
pad_height = delta_height // 2 | |
padding = (pad_width, pad_height, delta_width - pad_width, delta_height - pad_height) | |
return ImageOps.expand(img, padding) | |
def resize_with_padding(img, expected_size): | |
img.thumbnail((expected_size[0], expected_size[1])) | |
# print(img.size) | |
delta_width = expected_size[0] - img.size[0] | |
delta_height = expected_size[1] - img.size[1] | |
pad_width = delta_width // 2 | |
pad_height = delta_height // 2 | |
padding = (pad_width, pad_height, delta_width - pad_width, delta_height - pad_height) | |
return ImageOps.expand(img, padding) | |
if __name__ == "__main__": | |
img = Image.open("./demo.jpg") | |
print(img) | |
img = resize_with_padding(img, (500, 400)) | |
print(img.size) | |
img.show() | |
img.save("resized_img.jpg") |
Thanks a bunch Will !
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, @RamSasanka, you can use fill = (255,255,255) to set white color in padding instead of black.