Last week we’ve seen how to resize a picture using PIL.

Take a look to Resize an image using python to get more information on how to do this task.

Today I’m going to extend the previous program, I want to make a more general program, I want to pass the eight and width and I also want to apply the same resizing effect to a variable number of pictures.

resize

To do so, I need to read the command line arguments passed to the python script.

The new program will read the eight and the width from the first two cli arguments and will use them for the output files. All other arguments will be interpreted as file to resize.

To use the cli arguments I have to import the sys library (and naturally the Image library to resize the pictures)

import sys, Image

The arguments passed to the script will be stored int the sys.argv array. We can obtain more info typing the following code:

print 'Application name = ', sys.argv[0]
print '# of parameters  = ', len(sys.argv)
print 'argument list    = ', str(sys.argv)

Since argv[0] contains the Application name, argv[1] and argv[2] will contain width and eight.
The last arguments argv[3]……..argv[n] will be resized.
The new program will be the following:

##############################################################
# Automatic multi pictures resizing                          #
# www.xappsoftware.com/wordpress/                            #
##############################################################
import sys, Image
print 'Application name = ', sys.argv[0]
print '# of parameters  = ', len(sys.argv)
print 'argument list    = ', str(sys.argv)
 
# In the first two parameters there is the new size
# for the pictures
width  =  int(sys.argv[1])
height =  int(sys.argv[2])
 
# In the others parameters there are the filenames
# of the pictures we want to resize, so let's iterate
# between them
for i in range(3, len(sys.argv)):
    im1  =  Image.open(sys.argv[i])
    im2  =  im1.resize((width, height), Image.NEAREST)
    im2.save(sys.argv[1]+"x"+sys.argv[2]+sys.argv[i])

I’ve stored the program into a directory containing two png files (gg.png and marked.png)

gg1@gg1-VirtualBox:~/Desktop$ ls -al *png
-rw-rw-r-- 1 gg1 gg1 35974 Dec 27 22:57 gg.png
-rw-rw-r-- 1 gg1 gg1 41445 Dec 27 22:57 marked.png

Then ‘ve run the script

gg1@gg1-VirtualBox:~/Desktop$ python arg.py 50 50 *.png
Application name =  arg.py
# of parameters  =  5
argument list    =  ['arg.py', '50', '50', 'gg.png', 'marked.png']

And now the directory contains also the resized pictures.

gg1@gg1-VirtualBox:~/Desktop$ ls -al *png
-rw-rw-r-- 1 gg1 gg1  1032 Dec 28 12:27 50x50gg.png
-rw-rw-r-- 1 gg1 gg1  1111 Dec 28 12:27 50x50marked.png
-rw-rw-r-- 1 gg1 gg1 35974 Dec 27 22:57 gg.png
-rw-rw-r-- 1 gg1 gg1 41445 Dec 27 22:57 marked.png

Note that we are not handling errors, so you could have some errors while using this script. For example if you pass to the script an un-existent file.

That’s all.

Gg1