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!
import os, Image
def convert(path, format): for each in os.listdir(path): if each.endswith(format): try: name = os.path.join(path, each) save = os.path.splitext(name) Image.open(name).save(save + format) 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!