At my workplace, I’m bound to work with PHP but not at my home 😀 For PHP, I’ve seen cool image libraries like the GD library, ImageMagick and in-numerous classes to manipulate images. But what does Python have to offer when it comes to image manipulation ?
Python doesn’t have any native modules to work with images ( a big exception to the “batteries included” motto? ). PIL or the Python Imaging Library is the most popular one I found. It’s just awesome. It will remind you the difference between Python and other programming languages. I was seeking a solution to convert my php image resizing script into Python. I want to distribute the solution among my non techie friends. PHP is overkill for them though I could build a php-gtk app for easy use. But still, the runtime would have been heavy. And I always like Python for distributable apps.
When I looked into the PIL, I was surprised to see how easy it is to resize images. No need to dive deep into the basics of image manipulation. Just open a image and use the resize() method.
Have a look:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import Image,glob files = glob.glob("*.JPG") # Find all the JPG images in the directory width = 500 # new width height = 420 # new height ext = ".jpg" # target extension for imageFile in files: print "Processing: " + imageFile try: im = Image.open(imageFile) im = im.resize((width, height), Image.ANTIALIAS) # best down-sizing filter im.save(imageFile + ".resized" + ext) except Exception as exc: print "Error: " + str(exc) |
Isn’t it easy?
To run it, you need the PIL. For Ubuntu, get it by typing:
1 |
sudo apt-get install python-imaging |
For Windows and other platforms look here:
http://www.pythonware.com/products/pil/index.htm
Enjoy! 😀