I'm trying to take an image file, do some stuff to it and save the changes back to the original file. The problem I'm having is in overwriting the original image; there doesn't seem to be a reliable way to release the handle on filename
.
I need this content to be saved back to the same file because external processes depend on that filename to stay the same.
def do_post_processing(filename):
image = Image.open(str(filename))
try:
new_image = optimalimage.trim(image)
except ValueError as ex:
# The image is a blank placeholder image.
new_image = image.copy()
new_image = optimalimage.rescale(new_image)
new_image.save('tmp.tif')
del image
os.remove(str(filename))
os.rename('tmp.tif', str(filename))
del image
was working until I added the exception handler where I made a copy of the image. I've also tried accessing a close()
attribute of Image and with image
, no success.
You can provide a file-like object instead of a filename to the Image.open
function. So try this:
def do_post_processing(filename):
with open(str(filename), 'rb') as f:
image = Image.open(f)
...
del new_image, image
os.remove(str(filename))
os.rename(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With