Closed CoinCheung closed 1 week ago
What is the error/warning that you are seeing?
@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'>
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.
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?
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
The context manager of the with
applies to the initial image. After img = img.convert('RGB')
, img
no longer refers to the initial image.
Thanks!!
My code is like this:
my PIL version is: 10.4.0, and the image is:
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?