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.
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:
Since argv contains the Application name, argv and argv will contain width and eight.
The new program will be the following:
I’ve stored the program into a directory containing two png files (gg.png and marked.png)
Then ‘ve run the script
And now the directory contains also the resized pictures.
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.