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

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

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

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

【问题讨论】:

    标签: python python-imaging-library 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,请确保您不会混淆这两个包。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2015-04-13
    相关资源
    最近更新 更多