Skip to content

Commit 0c8be38

Browse files
authored
Merge pull request #7999 from radarhere/accept
Added MPEG accept function
2 parents 5e48d54 + c6a3f0f commit 0c8be38

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Tests/test_file_mpeg.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from __future__ import annotations
2+
3+
from io import BytesIO
4+
5+
import pytest
6+
7+
from PIL import Image, MpegImagePlugin
8+
9+
10+
def test_identify() -> None:
11+
# Arrange
12+
b = BytesIO(b"\x00\x00\x01\xb3\x01\x00\x01")
13+
14+
# Act
15+
with Image.open(b) as im:
16+
# Assert
17+
assert im.format == "MPEG"
18+
19+
assert im.mode == "RGB"
20+
assert im.size == (16, 1)
21+
22+
23+
def test_invalid_file() -> None:
24+
# Arrange
25+
invalid_file = "Tests/images/flower.jpg"
26+
27+
# Act / Assert
28+
with pytest.raises(SyntaxError):
29+
MpegImagePlugin.MpegImageFile(invalid_file)
30+
31+
32+
def test_load() -> None:
33+
# Arrange
34+
b = BytesIO(b"\x00\x00\x01\xb3\x01\x00\x01")
35+
36+
with Image.open(b) as im:
37+
# Act / Assert: cannot load
38+
with pytest.raises(OSError):
39+
im.load()

src/PIL/MpegImagePlugin.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ def read(self, bits: int) -> int:
5353
return v
5454

5555

56+
def _accept(prefix: bytes) -> bool:
57+
return prefix[:4] == b"\x00\x00\x01\xb3"
58+
59+
5660
##
5761
# Image plugin for MPEG streams. This plugin can identify a stream,
5862
# but it cannot read it.
@@ -77,7 +81,7 @@ def _open(self) -> None:
7781
# --------------------------------------------------------------------
7882
# Registry stuff
7983

80-
Image.register_open(MpegImageFile.format, MpegImageFile)
84+
Image.register_open(MpegImageFile.format, MpegImageFile, _accept)
8185

8286
Image.register_extensions(MpegImageFile.format, [".mpg", ".mpeg"])
8387

0 commit comments

Comments
 (0)