From ccb75705bd3bf40b31d800c6bacb7a91f30079e5 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sun, 2 Aug 2020 15:32:30 +1000 Subject: [PATCH] Added formats parameter to init --- Tests/test_image.py | 23 +++++++++++++++++++++++ src/PIL/Image.py | 20 +++++++++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/Tests/test_image.py b/Tests/test_image.py index 068fb8172..6b3148041 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -86,6 +86,29 @@ class TestImage: # with pytest.raises(MemoryError): # Image.new("L", (1000000, 1000000)) + def test_init(self): + try: + # No formats + Image.init([]) + assert len(Image.ID) == 0 + for ext in (".jpg", ".png"): + with pytest.raises(UnidentifiedImageError): + Image.open("Tests/images/hopper" + ext) + + # Only JPEG + Image.init(["JPEG"]) + assert len(Image.ID) != 0 + Image.open("Tests/images/hopper.jpg") + with pytest.raises(UnidentifiedImageError): + Image.open("Tests/images/hopper.png") + + finally: + # All formats + Image.init(True) + assert len(Image.ID) != 0 + for ext in (".jpg", ".png"): + Image.open("Tests/images/hopper" + ext) + def test_width_height(self): im = Image.new("RGB", (1, 2)) assert im.width == 1 diff --git a/src/PIL/Image.py b/src/PIL/Image.py index db639f524..b86b5a224 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -204,6 +204,7 @@ if hasattr(core, "DEFAULT_STRATEGY"): # Registries ID = [] +EVERY_ID = [] OPEN = {} MIME = {} SAVE = {} @@ -390,14 +391,24 @@ def preinit(): _initialized = 1 -def init(): +def init(formats=None): """ Explicitly initializes the Python Imaging Library. This function loads all available file format drivers. + + :param formats: Which formats to use when identifying images. The default value of + ``None`` will load all formats at first, or remember the previous + setting if called repeatedly. If you have previously provided a + list of formats to use, ``True`` must be used to remove the + restriction and use all formats. """ - global _initialized + global _initialized, ID, EVERY_ID if _initialized >= 2: + if formats is True: + ID = EVERY_ID + elif formats is not None: + ID = formats return 0 for plugin in _plugins: @@ -406,8 +417,11 @@ def init(): __import__("PIL.%s" % plugin, globals(), locals(), []) except ImportError as e: logger.debug("Image: failed to import %s: %s", plugin, e) + EVERY_ID = ID + if formats is not None and formats is not True: + ID = formats - if OPEN or SAVE: + if OPEN or SAVE or (not formats and formats is not None): _initialized = 2 return 1