Created
April 20, 2011 19:03
-
-
Save mattjmorrison/932345 to your computer and use it in GitHub Desktop.
Resize and Crop images with Python and PIL
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, 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