如何关闭图像?
问题描述:
我想拍摄一个图像文件,对它做一些东西并将更改保存回原始文件。我遇到的问题是覆盖原始图像;似乎没有一种可靠的方式来释放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))
del image
是工作,直到我说,我做的图像副本的异常处理程序。我也尝试访问Image和with image
的close()
属性,但没有成功。
答
您可以为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(...)
那么近我应该能够闻到它。 – Chris 2010-06-28 20:13:41