Auto-crop in PIL?

Fredrik Lundh fredrik at pythonware.com
Fri Oct 31 05:19:40 EST 2003


Kevin Smith wrote:

> Is there a way to "auto-crop" an image in PIL?  I have some PNG images
> with white backgrounds that I want cropped to show only the non-white
> portion in the center, but I don't see how I can do this.

import Image, ImageChops

##
# Crop borders off an image.
#
# @param im Source image.
# @param bgcolor Background color, using either a color tuple or
#     a color name (1.1.4 only).
# @return An image without borders, or None if there's no actual
#     content in the image.

def autocrop(im, bgcolor):
    if im.mode != "RGB":
        im = im.convert("RGB")
    bg = Image.new("RGB", im.size, bgcolor)
    diff = ImageChops.difference(im, bg)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)
    return None # no contents

</F>








More information about the Python-list mailing list