All Pages All Books|
|
||
|
import os, sys import Image
|
||
|
|
||
|
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".jpg" if infile != outfile: try:
Image.open(infile).save(outfile) except IOError:
print "cannot convert", infile
A second argument can be supplied to the save method which explicitly specifies a file format. If you use a non-standard extension, you must always specify the format this way:
Example: Create JPEG Thumbnails
import os, sys import Image
for infile in sys.argv[1:]:
outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try:
im = Image.open(infile) im.thumbnail((128, 128)) im.save(outfile, "JPEG") except IOError:
print "cannot create thumbnail for", infile
It is important to note is that the library doesn't decode or load the raster data unless it really has to. When you open a file, the file header is read to determine the file format and extract things like mode, size, and other properties required to decode the file, but the rest of the file is not processed until later.
This means that opening an image file is a fast operation, which is independent of the file size and compression type. Here's a simple script to quickly identify a set of image files:
Example: Identify Image Files
import sys import Image
for infile in sys.argv[1:]: try:
im = Image.open(infile)
print infile, im.format, "%dx%d" % im.size, im.mode except IOError:
pass
|
||
|
|
||
|
Cutting, Pasting and Merging Images
The Image class contains methods allowing you to manipulate regions within an image. To extract a sub-rectangle from an image, use the crop method.
Example: Copying a subrectangle from an image
|
||
|
|
||
All Pages All Books