[Image-SIG] Image.open fails when called more than 254 times

Fredrik Lundh fredrik at pythonware.com
Fri Sep 25 10:07:13 CEST 2009


On Mon, Sep 21, 2009 at 4:43 AM, Jeff Mathews <jeffm at fifengr.com> wrote:
> Using PIL 1.1.6 and the code...
> image = Image.open(filename)
> This works well, until the 255th time.  All subsequent calls fail with
> IOError.  Is this a bug in PIL? I am trying to load several hundred images
> and best fit rectangle pack them so it's best to open them all at once.

Please quote the entire error message so we don't have to guess what's
happening on your machine.

In this case, I assume you're running out of file handles.  PIL uses
lazy loading, so this is expected if you open many files without doing
anything with them (even if the limit is usually higher than 254
handles).   To work around this, make sure to explicitly load the
image into memory before you open the next one.  E.g. instead of doing

    for filename in long list:
        images.append(Image.open(filename))

in a big loop, do

    for filename in long list:
        im = Image.open(filename)
        im.load()
        images.append(im)

Alternatively, if you just need one or more attributes, copy the
attributes from the image object and leave the rest to the garbage
collector:

    for filename in long list:
        im = Image.open(filename)
        sizes.append(im.size)
        # the gc will release im on the next round through the for loop

</F>


More information about the Image-SIG mailing list