views:

37

answers:

1

I have a model with two image fields, a source image and a thumbnail.

When I update the new source image, save it and then try to read the source image to crop/scale it to a thumbnail I get an "I/O operation on closed file" error from PIL.

If I update the source image, don't save the source image, and then try to read the source image to crop/scale, I get an "attempting to read from closed file" error from PIL.

In both cases the source image is actually saved and available in later request/response loops.

If I don't crop/scale in a single request/response loop but instead upload on one page and then crop/scale in another page this all works fine.

This seems to be a cached buffer being reused some how, either by PIL or by the Django file storage. Any ideas on how to make an ImageField readable after saving?

More information ... ImageField is clearly closing the underlying file after saving. Is there any way to force a refresh of the ImageField? I see a few people using seek(0) but that will not work in this case.

A: 

There is a bug in the ImageField which I've tracked down and submitted to the django project.

If you have a simple model with an ImageField?, the following code will fail with a "I/O operation on closed file":

instance = MyClass.objects.get(...)
w = instance.image.width
h = instance.image.height
original = Image.open(instance.image)

The work around is to reopen the file:

instance = MyClass.objects.get(...)
w = instance.image.width
h = instance.image.height
instance.image.open()
original = Image.open(instance.image)
Rob Osborne