When I was writing the Font Awesome to PNG utility, I used a nice image processing library for Python — Python Imaging Library (PIL). It offers a lot of features, is easy to use, and comes with good documentation. And since it’s rather popular, there are many code examples for it all around the intertubes.
I couldn’t, however, find a comprehensive example of implementing an auto-crop feature for transparent images (specifically, PNG icons with a transparent background), so when I managed to put it together based on a few other examples, I thought I’d post it here in case anyone else finds it useful. So, here’s a function that autocrops a PIL image, optionally with a “border” of empty space around the contents:
def autocrop_image(image, border = 0): # Get the bounding box bbox = image.getbbox() # Crop the image to the contents of the bounding box image = image.crop(bbox) # Determine the width and height of the cropped image (width, height) = image.size # Add border width += border * 2 height += border * 2 # Create a new image object for the output image cropped_image = Image.new("RGBA", (width, height), (0,0,0,0)) # Paste the cropped image onto the new image cropped_image.paste(image, (border, border)) # Done! return cropped_image
And here’s a sample program that uses it:
#!/usr/bin/env python import sys import Image def autocrop_image(image, border = 0): ... if len(sys.argv) < 3: # Not enough arguments -- show usage information and exit print "Usage: " + sys.argv + " infile outfile [border]" exit(1) # Get input and output file names infile = sys.argv outfile = sys.argv # Check if border size was provided if sys.argv: border = int(sys.argv) else: border = 0 # Open the input image image = Image.open(infile) # Do the cropping image = autocrop_image(image, border) # Save the output image image.save(outfile)
Disclaimer: I’m a Python noob. If you find something wrong about the above code, let me know.