Introduction to Image Operations in Python

This is an article on Introduction to Image Operations in Python in Python.

Image manipulation is an interesting subject, as well almost inevitable in today's websites, you can use it to render CAPTCHA, crop & resize images, convert between image formats and many more advanced functions. Python with it's growing popularity has encouraged the community & enterprises to come up with modules for image processing in Python, there are many available modules in Python which will help you manipulate images, but in this article we'll be looking into the Python Imaging Library developed by pythonware.com. PIL is able to read a large number of image formats, but it has been restricted to writing out to only the popular formats.

Installing Python Imaging Library

Get the latest stable version of PIL from http://www.pythonware.com/products/pil/. Make sure you have Python development files on your system, in case you installed a Python binary. Untar & run python setup.py install, in case you run into any problem or you would like to customize your installation please refer to the README.

Basic Usage

By basic usage I mean opening an image, identifying the format, creating thumbnail, writing out in a different format than the source, etc. I can explain the functions but that is already done in the PIL documentation, so like always let me help you understand using a demo program with comments at appropriate places.

Code: Python

import Image

## the image being used in the demo is the G4E banner image http://i1.g4estatic.com/bannertm.gifpath_to_image = '/tmp/pradeep/bannertm.gif'

## save the file in the path specified, if you do not specify the output format## PIL will try to guess it from the output filenameimg.save(thumb_image_path, "JPEG")

Advanced Functions

There are a wide variety of advanced functions available in PIL, but it is out of the scope of this article to cover all the functions, so here we'll be looking into some popular operations like crop, image transform etc. Please follow the code sample below: