Skip to content

Instantly share code, notes, and snippets.

@fabeat
Forked from enagorny/scale.py
Created September 19, 2013 10:13
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save fabeat/6621507 to your computer and use it in GitHub Desktop.
Save fabeat/6621507 to your computer and use it in GitHub Desktop.
from PIL import Image
def scale(image, max_size, method=Image.ANTIALIAS):
"""
resize 'image' to 'max_size' keeping the aspect ratio
and place it in center of white 'max_size' image
"""
im_aspect = float(image.size[0])/float(image.size[1])
out_aspect = float(max_size[0])/float(max_size[1])
if im_aspect >= out_aspect:
scaled = image.resize((max_size[0], int((float(max_size[0])/im_aspect) + 0.5)), method)
else:
scaled = image.resize((int((float(max_size[1])*im_aspect) + 0.5), max_size[1]), method)
offset = (((max_size[0] - scaled.size[0]) / 2), ((max_size[1] - scaled.size[1]) / 2))
back = Image.new("RGB", max_size, "white")
back.paste(scaled, offset)
return back
@cactiball
Copy link

Thanks a lot.

@bezero
Copy link

bezero commented Mar 13, 2018

Alternative:

def scale(image, max_size, method=Image.ANTIALIAS):
    """
    resize 'image' to 'max_size' keeping the aspect ratio
    and place it in center of white 'max_size' image
    """
    image.thumbnail(max_size, method)
    offset = (int((max_size[0] - image.size[0]) / 2), int((max_size[1] - image.size[1]) / 2))
    back = Image.new("RGB", max_size, "white")
    back.paste(image, offset)

    return back

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