Sunday, April 29, 2007

[python] image converter

[This post has been translocated from my python blog to this blog, as I'm planning to close down my python blog.. It's not seeing much attention from me anyways :D ]

The following is a code for an image format converter cum resizing program. It takes a source directory, a destination directory and a target file format as parameters and converts all images in the source directory to the target format and writes them at the destination, after resizing them.

This is only a prototypical version and is rather rigid. You might have to modify it to suit your requirements.

Also note that the program requires Python Image Library (PIL) installed in addition to python.

import os
import Image

def imageConvert (source, dest, ext):
if os.path.isdir(source) and os.path.isdir(dest):
result = [True,[]]
for i in os.listdir(source):
if os.path.isdir(source + os.sep + i) == False:
outfile = dest + os.sep + \
os.path.splitext(i)[0] + ext
infile = source + os.sep + i
if infile != outfile:
im =
if ( im.size == (1024,768) ):
# Landscape Image
im = im.resize( (640,480) )
elif ( im.size == (768,1024) ):
# Portrait Image
im = im.resize( (480,640) )
except :
result[0] = False
result[1].append('cannot convert %s'\
% infile)
return result
return [False, ['Error, either the source or the' + \
'destination given is not a directory']]

def main ():
source = raw_input('Enter source directory: ')
dest = raw_input('Enter destination directory: ')
ext = '.' + raw_input('Enter file format extension: ')
r,l = imageConvert ( source, dest, ext )
if r == False:
for i in range(len(l)):
print l[i]

if __name__ == '__main__':

No comments: