Skip to content

Unpopular formats argument of PIL.Image.open cause exceptions #5036

@tsangwpx

Description

@tsangwpx

In open(), preinit() only initialize popular formats,
_open_core() will raise if the given formats have not been initialized. The init() failback become unreachable.

Pillow/src/PIL/Image.py

Lines 2901 to 2934 in 2d6e51e

preinit()
accept_warnings = []
def _open_core(fp, filename, prefix, formats):
for i in formats:
try:
factory, accept = OPEN[i]
result = not accept or accept(prefix)
if type(result) in [str, bytes]:
accept_warnings.append(result)
elif result:
fp.seek(0)
im = factory(fp, filename)
_decompression_bomb_check(im.size)
return im
except (SyntaxError, IndexError, TypeError, struct.error):
# Leave disabled by default, spams the logs with image
# opening failures that are entirely expected.
# logger.debug("", exc_info=True)
continue
except BaseException:
if exclusive_fp:
fp.close()
raise
return None
im = _open_core(fp, filename, prefix, formats)
if im is None:
if init():
im = _open_core(fp, filename, prefix, formats)

What did you do?

from __future__ import annotations

from PIL import Image


def main():
    with open('any.webp', 'rb') as f:
        try:
            im = Image.open(f, formats=('WEBP',))
        except Exception:
            print(Image.ID)  # No WEBP in the list
            raise
        else:
            print(im.size)


if __name__ == '__main__':
    main()

What did you expect to happen?

Output the size

(640, 480)

What actually happened?

['BMP', 'DIB', 'GIF', 'TIFF', 'JPEG', 'PPM', 'PNG']
Traceback (most recent call last):
  File "pil_debug.py", line 18, in <module>
    main()
  File "pil_debug.py", line 9, in main
    im = Image.open(f, formats=('WEBP',))
  File "lib\site-packages\PIL\Image.py", line 2929, in open
    im = _open_core(fp, filename, prefix, formats)
  File "lib\site-packages\PIL\Image.py", line 2909, in _open_core
    factory, accept = OPEN[i]
KeyError: 'WEBP'

What are your OS, Python and Pillow versions?

  • OS: Windows 10
  • Python: 3.8
  • Pillow: 8.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions