From fedb0407b4cd14a285fbc641761d9bc6a5348c37 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Thu, 26 Dec 2019 13:10:39 +1100 Subject: [PATCH] Raise ValueError for io.StringIO in Image.open --- Tests/test_image.py | 4 ++++ src/PIL/Image.py | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/Tests/test_image.py b/Tests/test_image.py index 83da76b96..47e7420ef 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -1,3 +1,4 @@ +import io import os import shutil import tempfile @@ -91,6 +92,9 @@ class TestImage(PillowTestCase): def test_bad_mode(self): self.assertRaises(ValueError, Image.open, "filename", "bad mode") + def test_stringio(self): + self.assertRaises(ValueError, Image.open, io.StringIO()) + def test_pathlib(self): from PIL.Image import Path diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 41e9c9fe8..3827ab09d 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -2690,10 +2690,16 @@ def open(fp, mode="r"): :exception FileNotFoundError: If the file cannot be found. :exception PIL.UnidentifiedImageError: If the image cannot be opened and identified. + :exception ValueError: If the ``mode`` is not "r", or if a StringIO + instance is used for ``fp``. """ if mode != "r": raise ValueError("bad mode %r" % mode) + elif isinstance(fp, io.StringIO): + raise ValueError( + "StringIO cannot be used to open an image. Binary data must be used instead" + ) exclusive_fp = False filename = ""