diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py index e6ab1c915e6..40407da0c20 100644 --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -2,6 +2,7 @@ import os import re +import struct import warnings from io import BytesIO from pathlib import Path @@ -766,6 +767,18 @@ def test_bad_mpo_header(self) -> None: im.close() + def test_mp_entry_count_too_high(self) -> None: + """Treat an MPO with fewer MP entries than images as JPEG""" + with open("Tests/images/sugarshack.mpo", "rb") as fp: + data = fp.read() + + # Change the number of images to three, without adding a third MP entry + data = data[:6048] + struct.pack(">L", 3) + data[6052:] + + with pytest.warns(UserWarning, match="malformed MPO file"): + with Image.open(BytesIO(data)) as im: + assert im.format == "JPEG" + @pytest.mark.parametrize("mode", ("1", "L", "RGB", "RGBX", "CMYK", "YCbCr")) def test_save_correct_modes(self, mode: str) -> None: out = BytesIO() diff --git a/src/PIL/JpegImagePlugin.py b/src/PIL/JpegImagePlugin.py index 46320eb3b5b..c0802f4e6a0 100644 --- a/src/PIL/JpegImagePlugin.py +++ b/src/PIL/JpegImagePlugin.py @@ -605,7 +605,7 @@ def _getmp(self: JpegImageFile) -> dict[int, Any] | None: mpentry["Attribute"] = mpentryattr mpentries.append(mpentry) mp[0xB002] = mpentries - except KeyError as e: + except (KeyError, struct.error) as e: msg = "malformed MP Index (bad MP Entry)" raise SyntaxError(msg) from e # Next we should try and parse the individual image unique ID list;