76

I have a python file with the Pillow library imported. I can open an image with

Image.open(test.png)

But how do I close that image? I'm not using Pillow to edit the image, just to show the image and allow the user to choose to save it or delete it.

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
Chase Cromwell
  • 1,021
  • 1
  • 7
  • 15

2 Answers2

139

With Image.close()

You can also do it in a with block:

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

An example of using Image.close():

test = Image.open('test.png')
test.close()
phoenix
  • 7,988
  • 6
  • 39
  • 45
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
  • I always use the second option. Context managers are really nice. – Brobin Jul 31 '15 at 17:03
  • @Brobin Oh yeah, with blocks are the way to go. And also one of the things I miss most when I have to use another language. – Morgan Thrapp Jul 31 '15 at 17:04
  • 1
    Using "with" I get an "AttributeError: __exit__" Error with PIL 1.1.7, which version do you use? – Chris Aug 03 '17 at 13:36
  • 2
    I know this a really old post but on my Mac .close() doesn't do anything. The File opens in the Preview and stays open after calling .close(). – Difio Jun 01 '22 at 10:48
-8

If you create a PIL object you will see there is no close method.

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']
  • There is though, take a look at the [docs](https://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.close). I'm not sure why it doesn't show up in the directory of the object, but it definitely exists. – Morgan Thrapp Jul 07 '16 at 13:00
  • 6
    My Pillow(version 2.3.0) seems missing the close method, too. – Roger Huang Jul 25 '16 at 03:42
  • I'm using pkg_resources to check its version: >>> pkg_resources.get_distribution('Pillow').version '2.3.0' – Roger Huang Jul 25 '16 at 03:42
  • In my case I was also using PGMagick so make sure you're not confusing the two packages if you're converting to PDF. – dev-jeff Oct 27 '20 at 16:39