Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Close an Image?

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.

like image 521
Chris Avatar asked Jun 28 '10 19:06

Chris


1 Answers

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(...)
like image 77
David Z Avatar answered Oct 09 '22 14:10

David Z