diff --git a/PIL/Image.py b/PIL/Image.py index 06bf7ce94..d90996a57 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1620,13 +1620,17 @@ class Image(object): """ filename = "" + open_fp = False if isPath(fp): filename = fp + open_fp=True elif sys.version_info >= (3, 4): from pathlib import Path if isinstance(fp, Path): filename = str(fp.resolve()) + open_fp=True elif hasattr(fp, "name") and isPath(fp.name): + # only set the name for metadata purposes filename = fp.name # may mutate self! @@ -1655,17 +1659,14 @@ class Image(object): else: save_handler = SAVE[format.upper()] - if filename: + if open_fp: fp = builtins.open(filename, "wb") - close = 1 - else: - close = 0 try: save_handler(self, fp, filename) finally: # do what we can to clean up - if close: + if open_fp: fp.close() def seek(self, frame): diff --git a/Tests/test_image.py b/Tests/test_image.py index fa7f8ec06..59ffcd114 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -57,6 +57,17 @@ class TestImage(PillowTestCase): self.assertEqual(im.mode, "RGB") self.assertEqual(im.size, (128, 128)) + def test_tempfile(self): + # see #1460, pathlib support breaks tempfile.TemporaryFile on py27 + # Will error out on save on 3.0.0 + import tempfile + im = hopper() + fp = tempfile.TemporaryFile() + im.save(fp, 'JPEG') + fp.seek(0) + reloaded = Image.open(fp) + self.assert_image_similar(im, reloaded, 20) + def test_internals(self): im = Image.new("L", (100, 100))