python-pillow / Pillow

Python Imaging Library (Fork)
https://python-pillow.org
Other
12.27k stars 2.23k forks source link

How could I eliminate this error message? #8540

Open CoinCheung opened 3 hours ago

CoinCheung commented 3 hours ago

My code is like this:

from PIL import Image
import warnings
warnings.filterwarnings("error")

pth = 'image_013493346.png'
img = Image.open(pth)
img = img.convert('RGB')
img.save('tmp.jpg')
img.close()

my PIL version is: 10.4.0, and the image is: image_013493346

I did not observe same problem with other images, only this one. Is there any problem with this image? How could I avoid this error?

radarhere commented 2 hours ago

What is the error/warning that you are seeing?

CoinCheung commented 2 hours ago

@radarhere

Exception ignored in: <_io.FileIO name='image_013493346.png' mode='rb' closefd=True>
Traceback (most recent call last):
  File "tmp.py", line 8, in <module>
    img = img.convert('RGB')
ResourceWarning: unclosed file <_io.BufferedReader name='image_013493346.png'>
radarhere commented 2 hours ago

You can change

img = Image.open(pth)
img = img.convert('RGB')
img.save('tmp.jpg')
img.close()

to

with Image.open(pth) as img:
    img = img.convert('RGB')
    img.save('tmp.jpg')

While I appreciate that you were trying to call img.close(), img = img.convert('RGB') meant that you were calling it on a copy of the image, not the original image that was opened from the file.

CoinCheung commented 2 hours ago

Actually, I need to read image, and check it and return the image object to other function. Can the img object live out of the with statement?

radarhere commented 1 hour ago

You can

with Image.open(pth) as img:
    img = img.convert('RGB')
img.save('tmp.jpg')
img.close()

Or you can

img = Image.open(pth)
img2 = img.convert('RGB')
img.close()
img2.save('tmp.jpg')
img2.close()

You can read more about this at https://pillow.readthedocs.io/en/stable/deprecations.html#image-del