Speeding up Initialization
Fredrik Lundh | Updated April 10, 1997
Importing the Image module is usually a pretty fast operation, but the first time you try to open or save a file (whatever comes first), you may have to wait 1-5 seconds for PIL to pull in all its file format plugins.
If you create simple scripts that only loads a single image, and processes it in some simple fashion, this may account for most of the execution time. However, if you know for sure that you will only handle a few file formats, you can use the following trick to speed things up:
- Import the Image module
- Explicitly import the plugins you need. For example, to enable GIF support, include GifImagePlugin. You’ll find the available plugins in the Lib directory.
- Set the Image._initialized flag to 1.
The following script explicitly imports handlers for GIF, JPEG, and PNG, which are the major file formats used on the World Wide Web.
# Example: enabling only web-related file format handlers import Image # import web-related file formats import GifImagePlugin import JpegImagePlugin import PngImagePlugin # don't look for more plugins Image._initialized = 1 # open using one the explicitly imported plugins im = Image.open("python.gif")
Changes in 0.3 and later
Starting with version 0.3, PIL automatically preinstalls handlers for the most common file formats, including BMP, GIF, JPEG, PNG, and PPM. Only if a file cannot be opened by any of these, the rest of the plugins will be loaded. To force loading, call the Image.init function.