From 88ec0bb52fe9c4a37e1d10c68f0dc99dfa306597 Mon Sep 17 00:00:00 2001 From: homm Date: Sun, 17 Jul 2016 06:29:36 +0300 Subject: [PATCH] close file in case of failures --- PIL/Image.py | 5 +++++ PIL/ImageFile.py | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/PIL/Image.py b/PIL/Image.py index 1c6019a10..c1dd9e3d1 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -2391,6 +2391,7 @@ def open(fp, mode="r"): if mode != "r": raise ValueError("bad mode %r" % mode) + exclusive_fp = False filename = "" if isPath(fp): filename = fp @@ -2404,11 +2405,13 @@ def open(fp, mode="r"): if filename: fp = builtins.open(filename, "rb") + exclusive_fp = True try: fp.seek(0) except (AttributeError, io.UnsupportedOperation): fp = io.BytesIO(fp.read()) + exclusive_fp = True prefix = fp.read(16) @@ -2439,6 +2442,8 @@ def open(fp, mode="r"): if im: return im + if exclusive_fp: + fp.close() raise IOError("cannot identify image file %r" % (filename if filename else fp)) diff --git a/PIL/ImageFile.py b/PIL/ImageFile.py index 9425669e2..57391bcce 100644 --- a/PIL/ImageFile.py +++ b/PIL/ImageFile.py @@ -88,10 +88,12 @@ class ImageFile(Image.Image): # filename self.fp = open(fp, "rb") self.filename = fp + self._exclusive_fp = True else: # stream self.fp = fp self.filename = filename + self._exclusive_fp = False try: self._open() @@ -100,6 +102,9 @@ class ImageFile(Image.Image): KeyError, # unsupported mode EOFError, # got header but not the first frame struct.error) as v: + # close the file only if we have opened it this constructor + if self._exclusive_fp: + self.fp.close() raise SyntaxError(v) if not self.mode or self.size[0] <= 0: