Quite a cryptic title, but if you haven’t guessed, were talking about Images. This being a Python article that’s what we're using! If you’ve never thought about it, or -- even better -- if you didn’t know it was possible then you’re in for a nice surprise; not only can Python do this but it’s pretty good at it, too. Actually, Python works well with graphics in general, but for now we’re sticking to the 2D kind.
Who ever said programming had to be hard work? With a little help from the OS module we can turn this into a nice piece of batch processing!
#!/usr/bin/env python
import os, Image
def convert(path, format): for each in os.listdir(path): if each.endswith(format[0]): try: name = os.path.join(path, each) save = os.path.splitext(name) Image.open(name).save(save[0] + format[1]) except IOError: None
if __name__ == '__main__':
convert('', ('.jpg', '.gif'))
Ok, possibly a little scary at first glance but all this actually does is read a list of names from a given directory and loops over them performing some action. convert() just checks if 'each' ends with the extension we want before joining 'path' and 'each' together and splitting the extension from end. It then attempts to convert the image using PIL.
And no, you're not limited to converting images between formats, or PIL would be pretty useless wouldn't it! Actually one of the things I like most about PIL is that it hides a lot of the complexities that pop up when you're working with images. That said let's have a look at some of the other things we can do!
This shows off some nice features i.e. retrieving the image size, actual format, resizing, etc. The next part (after image.mode) does the actual work: resizing, cropping and rotating the image.