Skip to content

Instantly share code, notes, and snippets.

@InputBlackBoxOutput
Created October 12, 2021 02:54
Show Gist options
  • Save InputBlackBoxOutput/147edbd8c9caedabdc04e3b8ef5344af to your computer and use it in GitHub Desktop.
Save InputBlackBoxOutput/147edbd8c9caedabdc04e3b8ef5344af to your computer and use it in GitHub Desktop.
Resize an image to a square image with the help of minimal padding
from PIL import Image
def resize_image(img_path, desired_size = 300, background_color=None):
img = Image.open(img_path)
old_size = img.size
if background_color == None:
background_color = img.load()[0,0]
ratio = float(desired_size-10)/max(old_size)
new_size = tuple([int(x*ratio) for x in old_size])
img = img.resize(new_size, Image.ANTIALIAS)
output = Image.new("RGB", (desired_size, desired_size), color=background_color)
output.paste(img, ((desired_size-new_size[0])//2, (desired_size-new_size[1])//2))
return output
if __name__ == '__main__':
img = resize_image("image.png", background_color=(255, 255, 255))
img.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment