Things about me, the web and the wonderful world of software development.
 

Image Conversion in Python

Yesterday I had to convert a lot of pictures to different formats. I quickly came up with a Python Script that searches a specified path recursively for images and converts them to one or more output formats. It's nothing fancy and it was late at night so don't blame me for bad code. I just thought I'd share it here because it might be useful for someone. In order to run this script you need to have PIL installed.

class ImageConverter(object):

def __init__(self, types_in, types_out):
self.types_in = types_in
self.types_out = types_out

def search_files(self, path):
if path[-1] != '/':
path += '/'

print "searching files in " + path
for root, dirs, files in os.walk(path):
for fname in files:
fullpath = os.path.join(root, fname)
if os.path.splitext(fname)[1] in self.types_in:
self.convert_image(fullpath)
def convert_image(self, filepath):

for t in self.types_out:
outfile = os.path.splitext(filepath)[0] + t.lower()
print "converting image %s to %s" % (filepath, outfile)

try:
im = Image.open(filepath)
im.save(outfile)
except IOError as detail:
print "Failed to convert image %s to %s. Details: %s" % (filepath, outfile, detail)

except:
print "Unexpected error: ", sys.exc_info()[0]
raise
if __name__ == '__main__':
if len(sys.argv) == 1 or len(sys.argv) > 2:
print 'Usgae: python ' + str(sys.argv[0]) + ' /path/to/search/'
else:
converter = ImageConverter(['.gif',], ['.tiff',])
converter.search_files(sys.argv[1])

I think the script is pretty self-explanatory. Simply pass the path to search for images as a command line argument. When instantiating the class, the input and output formats can be specified as a list.

I think that's it for today.

 Tags: python

« Go Back