Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL throws ValueError: seek of closed file

My program throws an exception on line

img.save(path)

where img is a PIL.Image and path is a string storing a valid path.

This is the entire exception stack:

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

Any advise on what might be causing this issue?

like image 450
grześ Avatar asked Oct 20 '25 09:10

grześ


1 Answers

jasonharper's suggestion in a comment was actually a solution!

The code comes from a Flask app and the image was opened in these lines:

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.")

Adding img.load() after img = Image.open(f) solved my issue.

like image 78
grześ Avatar answered Oct 23 '25 01:10

grześ