Skip to content

Instantly share code, notes, and snippets.

@mattjmorrison
Created April 20, 2011 19:03
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mattjmorrison/932345 to your computer and use it in GitHub Desktop.
Save mattjmorrison/932345 to your computer and use it in GitHub Desktop.
Resize and Crop images with Python and PIL
from PIL import Image, ImageChops
def trim(im, border):
bg = Image.new(im.mode, im.size, border)
diff = ImageChops.difference(im, bg)
bbox = diff.getbbox()
if bbox:
return im.crop(bbox)
def create_thumbnail(path, size):
image = Image.open(path)
name, extension = path.split('.')
options = {}
if 'transparency' in image.info:
options['transparency'] = image.info["transparency"]
image.thumbnail((size, size), Image.ANTIALIAS)
image = trim(image, 255) ## Trim whitespace
image.save(name + '_new.' + extension, **options)
return image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment