Tutorial
Using the Image Class
The most important class in the Python Imaging Library is the Image class, defined in the
module with the same name. You can create instances of this class in several ways; either
by loading images from files, processing other images, or creating images from scratch.
To load an image from a file, use the open function in the Image module.
>>> import Image
>>> im = Image.open("lena.ppm")
If successful, this function returns an Image object. You can now use instance attributes
to examine the file contents.
>>> print im.format, im.size, im.mode
PPM (512, 512) RGB
The format attribute identifies the source of an image. If the image was not read from a
file, it is set to None. The size attribute is a 2-tuple containing width and height (in
pixels). The mode attribute defines the number and names of the bands in the image, and
also the pixel type and depth. Common modes are "L" (luminance) for greyscale images,
"RGB" for true colour images, and "CMYK" for pre-press images.
If the file cannot be opened, an IOError exception is raised.
Once you have an instance of the Image class, you can use the methods defined by this
class to process and manipulate the image. For example, let's display the image we just
loaded:
>>> im.show()
(The standard version of show is not very efficient, since it saves the image to a
temporary file and calls the xv utility to display the image. If you don't have xv installed,
it won't even work. When it does work though, it is very handy for debugging and tests.)
The following sections provide an overview of the different functions provided in this
library.
Reading and Writing Images
The Python Imaging Library supports a wide variety of image file formats. To read files
from disk, use the open function in the Image module. You don't have to know the file
format to open a file. The library automatically determines the format based on the
contents of the file.
To save a file, use the save method of the Image class. When saving files, the name
becomes important. Unless you specify the format, the library uses the filename extension
to discover which file storage format to use.
Example: Convert files to JPEG
评论