Skip to content

Instantly share code, notes, and snippets.

@BIGBALLON
Last active June 28, 2022 19:20
Show Gist options
  • Save BIGBALLON/cb6ab73f6aaaa068ab6756611bb324b2 to your computer and use it in GitHub Desktop.
Save BIGBALLON/cb6ab73f6aaaa068ab6756611bb324b2 to your computer and use it in GitHub Desktop.
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")
@RamSasanka
Copy link

Thanks a bunch Will !

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