如何关闭在 Pillow 中打开的图像?

Posted

技术标签:

【中文标题】如何关闭在 Pillow 中打开的图像?【英文标题】:How do I close an image opened in Pillow? 【发布时间】:2015-10-23 10:41:14 【问题描述】:

我有一个导入了 Pillow 库的 python 文件。我可以用

打开图片
Image.open(test.png)

但是如何关闭该图像?我没有使用 Pillow 来编辑图像,只是为了显示图像并允许用户选择保存或删除它。

【问题讨论】:

【参考方案1】:

Image.close().

您也可以在 with 块中执行此操作:

with Image.open('test.png') as test_image:
    do_things(test_image)

使用Image.close()的例子:

test = Image.open('test.png')
test.close()

【讨论】:

我总是使用第二个选项。上下文管理器真的很棒。 @Brobin 哦,是的,块是要走的路。当我不得不使用另一种语言时,这也是我最想念的事情之一。 使用“with”时,PIL 1.1.7 出现“AttributeError: exit”错误,您使用哪个版本?【参考方案2】:

如果您创建一个 PIL 对象,您将看到没有关闭方法。

from PIL import Image

img=Image.open("image.jpg")
dir(img)

['_Image__transformer', '_PngImageFile__idat', '__doc__', '__getattr__', '__init__', '__module__', '__repr__', '_copy', '_dump', '_expand', '_makeself', '_new', '_open', 'category', 'convert', 'copy', 'crop', 'decoderconfig', 'decodermaxblock', 'draft', 'filename', 'filter', 'format', 'format_description', 'fp', 'frombytes', 'fromstring', 'getbands', 'getbbox', 'getcolors', 'getdata', 'getextrema', 'getim', 'getpalette', 'getpixel', 'getprojection', 'histogram', 'im', 'info', 'load', 'load_end', 'load_prepare', 'load_read', 'map', 'mode', 'offset', 'palette', 'paste', 'png', 'point', 'putalpha', 'putdata', 'putpalette', 'putpixel', 'quantize', 'readonly', 'resize', 'rotate', 'save', 'seek', 'show', 'size', 'split', 'tell', 'text', 'thumbnail', 'tile', 'tobitmap', 'tobytes', 'tostring', 'transform', 'transpose', 'verify']

【讨论】:

有,看看docs。我不知道为什么它没有出现在对象的目录中,但它肯定存在。 My Pillow(version 2.3.0) 似乎也缺少 close 方法。 我正在使用 pkg_resources 来检查它的版本:>>> pkg_resources.get_distribution('Pillow').version '2.3.0' 在我的情况下,我也在使用 PGMagick,所以如果您要转换为 PDF,请确保您不会混淆这两个包。

以上是关于如何关闭在 Pillow 中打开的图像?的主要内容,如果未能解决你的问题,请参考以下文章

Pillow学习笔记一——入门

Pillow

Pillow

cv2 & PIL(pillow)显示图像

Python图像Pillow库

Python3 集成Pillow