From 196a48b4fd5cd388d5412d7aa0115e99b6e8c792 Mon Sep 17 00:00:00 2001 From: wiredfool Date: Fri, 28 Feb 2014 15:57:53 -0800 Subject: [PATCH] added context manager support --- PIL/Image.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/PIL/Image.py b/PIL/Image.py index 75e7efc75..d7435d1ef 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -497,6 +497,25 @@ class Image: _makeself = _new # compatibility + # with compatibility + def __enter__(self): + return self + def __exit__(self, *args): + self.close() + + def close(self): + """ Close the file pointer, if possible. Destroy the image core. + This releases memory, and the image will be unusable afterward + """ + try: + self.fp.close() + except Exception as msg: + if Image.DEBUG: + print ("Error closing: %s" %msg) + + self.im = None + + def _copy(self): self.load() self.im = self.im.copy()