Django gives “I/O operation on closed file” error when reading from a saved ImageField

左心房为你撑大大i 提交于 2020-01-12 07:26:47

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/3029988/django-gives-i-o-operation-on-closed-file-error-when-reading-from-a-saved-imag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!