- Python Multimedia
- Ninad Sathaye
- 779字
- 2025-03-31 06:21:37
Time for action – image file converter
With this basic information, let's build a simple image file converter. This utility will batch-process image files and save them in a user-specified file format.
To get started, download the file ImageFileConverter.py
from the Packt website, www.packtpub.com. This file can be run from the command line as:
python ImageConverter.py [arguments]
Here, [arguments]
are:
--input_dir
: The directory path where the image files are located.--input_format
: The format of the image files to be converted. For example,jpg
.--output_dir
: The location where you want to save the converted images.--output_format
: The output image format. For example,jpg
,png
,bmp,
and so on.
The following screenshot shows the image conversion utility in action on Windows XP, that is, running image converter from the command line.
Here, it will batch-process all the .jpg
images within C:\PythonTest\images
and save them in png
format in the directory C:\PythonTest\images\OUTPUT_IMAGES
.

The file defines class ImageConverter
. We will discuss the most important methods in this class.
def processArgs:
This method processes all the command-line arguments listed earlier. It makes use of Python's built-in modulegetopts
to process these arguments. Readers are advised to review the code in the fileImageConverter.py
in the code bundle of this book for further details on how these arguments are processed.def convertImage:
This is the workhorse method of the image-conversion utility.1 def convertImage(self): 2 pattern = "*." + self.inputFormat 3 filetype = os.path.join(self.inputDir, pattern) 4 fileList = glob.glob(filetype) 5 inputFileList = filter(imageFileExists, fileList) 6 7 if not len(inputFileList): 8 print "\n No image files with extension %s located \ 9 in dir %s"%(self.outputFormat, self.inputDir) 10 return 11 else: 12 # Record time before beginning image conversion 13 starttime = time.clock() 14 print "\n Converting images.." 15 16 # Save image into specified file format. 17 for imagePath in inputFileList: 18 inputImage = Image.open(imagePath) 19 dir, fil = os.path.split(imagePath) 20 fil, ext = os.path.splitext(fil) 21 outPath = os.path.join(self.outputDir, 22 fil + "." + self.outputFormat) 23 inputImage.save(outPath) 24 25 endtime = time.clock() 26 print "\n Done!" 27 print "\n %d image(s) written to directory:\ 28 %s" %(len(inputFileList), self.outputDir) 29 print "\n Approximate time required for conversion: \ 30 %.4f seconds" % (endtime – starttime)
Now let's review the preceding code.
- Our first task is to get a list of all the image files to be saved in a different format. This is achieved by using
glob
module in Python. Line 4 in the code snippet finds all the file path names that match the pattern specified by the local variablefileType
. On line 5, we check whether the image file infileList
exists. This operation can be efficiently performed over the whole list using the built-infilter
functionality in Python. - The code block between lines 7 to 14 ensures that one or more images exist. If so, it will record the time before beginning the image conversion.
- The next code block (lines 17-23) carries out the image file conversion. On line 18, we use
Image.open
to open the image file. Line 18 creates anImage
object. Then the appropriate output path is derived and finally the output image is saved using thesave
method of theImage
module.
What just happened?
In this simple example, we learned how to open and save image files in a specified image format. We accomplished this by writing an image file converter that batch-processes a specified image file. We used PIL's Image.open
and Image.save
functionality along with Python's built-in modules such as glob
and filter
.
Now we will discuss other key aspects related to the image reading and writing.
Creating an image from scratch
So far we have seen how to open an existing image. What if we want to create our own image? As an example, it you want to create fancy text as an image, the functionality that we are going to discuss now comes in handy. Later in this book, we will learn how to use such an image containing some text to embed into another image. The basic syntax for creating a new image is:
foo = Image.new(mode, size, color)
Where, new
is the built-in method of class Image
. Image.new
takes three arguments, namely, mode
, size
, and color
. The mode
argument is a string that gives information about the number and names of image bands. Following are the most common values for mode argument: L
(gray scale) and RGB
(true color). The size
is a tuple
specifying dimensions of the image in pixels, whereas, color
is an optional argument. It can be assigned an RGB value (a 3-tuple
) if it's a multi-band image. If it is not specified, the image is filled with black color.