tags:

views:

43

answers:

1

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.

+2  A: 

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(...)
David Zaslavsky
So close I should have been able to smell it.
phasetwenty