如何关闭图像?

Chr*_*ris 8 python python-imaging-library

我正在尝试获取图像文件,对其执行一些操作并将更改保存回原始文件.我遇到的问题是覆盖原始图像; 似乎没有一种可靠的方法来释放句柄filename.

我需要将此内容保存回同一文件,因为外部进程依赖于该文件名保持不变.

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))
Run Code Online (Sandbox Code Playgroud)

del image工作,直到我添加了异常处理程序,我在其中制作了图像的副本.我也试过访问close()Image的一个属性with image,但没有成功.

Dav*_*d Z 16

您可以为Image.open函数提供类文件对象而不是文件名.试试这个:

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(...)
Run Code Online (Sandbox Code Playgroud)