Python 如何关闭图像?
我正在尝试拍摄一个图像文件,对其进行一些处理,并将更改保存回原始文件。我遇到的问题是覆盖原始图像;似乎没有可靠的方法来释放Python 如何关闭图像?,python,python-imaging-library,Python,Python Imaging Library,我正在尝试拍摄一个图像文件,对其进行一些处理,并将更改保存回原始文件。我遇到的问题是覆盖原始图像;似乎没有可靠的方法来释放filename上的句柄 我需要将此内容保存回同一文件,因为外部进程依赖于该文件名保持不变 def do_post_processing(filename): image = Image.open(str(filename)) try: new_image = optimalimage.trim(image) except ValueE
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和Image的属性close()
,但没有成功。您可以为函数提供类似文件的对象,而不是文件名。所以试试这个:
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(...)
离得这么近,我应该能闻到它的味道。