PIL引发ValueError:查找关闭的文件

时间:2019-05-20 15:06:32

标签: python python-3.x python-imaging-library

我的程序在网上抛出异常

img.save(path)

其中img是PIL.Image,而path是存储有效路径的字符串。

这是整个异常堆栈:

Traceback (most recent call last):
  File "/home/grzes/repos/backend/server.py", line 109, in _run_job
    job.result = lambda_fun(job.progress)
  File "/home/grzes/repos/backend/server.py", line 224, in <lambda>
    return app.jobs_handler.create_job(lambda progress: run_prediction(img, progress))
  File "/home/grzes/repos/backend/server.py", line 251, in run_prediction
    img.save(path)
  File "/home/grzes/venv/lib/python3.5/site-packages/PIL/Image.py", line 1899, in save
    self.load()
  File "/home/grzes/venv/lib/python3.5/site-packages/PIL/ImageFile.py", line 206, in load
    seek(offset)
  File "/home/grzes/venv/lib/python3.5/tempfile.py", line 886, in seek
    self._file.seek(*args)
ValueError: seek of closed file

有什么建议可能导致此问题?

1 个答案:

答案 0 :(得分:0)

jasonharper 在评论中的建议实际上是一种解决方案!

该代码来自Flask应用,并且在以下行中打开了图像:

try:
    f = request.files['file']
    if f.filename == '':
        raise KeyError
except KeyError:
    return render_template('index.html', err_mssg="File not included")

try:
    img = Image.open(f)
except OSError:
    return render_template('index.html', err_mssg="File is not a valid image.")

img.load()之后添加img = Image.open(f)解决了我的问题。