20
20
from .deprecated import deprecate_with_version
21
21
22
22
23
- def _signature_matches_extension (filename ):
23
+ def _signature_matches_extension (filename , sniff ):
24
24
"""Check if signature aka magic number matches filename extension.
25
25
26
26
Parameters
27
27
----------
28
28
filename : str or os.PathLike
29
29
Path to the file to check
30
30
31
+ sniff : bytes or None
32
+ First bytes of the file. If not `None` and long enough to contain the
33
+ signature, avoids having to read the start of the file.
34
+
31
35
Returns
32
36
-------
33
37
matches : bool
@@ -50,11 +54,14 @@ def _signature_matches_extension(filename):
50
54
if ext not in signatures :
51
55
return True , ""
52
56
expected_signature = signatures [ext ]["signature" ]
53
- try :
54
- with open (filename , "rb" ) as fh :
55
- found_signature = fh .read (len (expected_signature ))
56
- except OSError :
57
- return False , f"Could not read file: { filename } "
57
+ if sniff is not None and len (sniff ) >= len (expected_signature ):
58
+ found_signature = sniff [:len (expected_signature )]
59
+ else :
60
+ try :
61
+ with open (filename , "rb" ) as fh :
62
+ found_signature = fh .read (len (expected_signature ))
63
+ except OSError :
64
+ return False , f"Could not read file: { filename } "
58
65
if found_signature == expected_signature :
59
66
return True , ""
60
67
format_name = signatures [ext ]["format_name" ]
@@ -85,9 +92,6 @@ def load(filename, **kwargs):
85
92
raise FileNotFoundError (f"No such file or no access: '{ filename } '" )
86
93
if stat_result .st_size <= 0 :
87
94
raise ImageFileError (f"Empty file: '{ filename } '" )
88
- matches , msg = _signature_matches_extension (filename )
89
- if not matches :
90
- raise ImageFileError (msg )
91
95
92
96
sniff = None
93
97
for image_klass in all_image_classes :
@@ -96,6 +100,10 @@ def load(filename, **kwargs):
96
100
img = image_klass .from_filename (filename , ** kwargs )
97
101
return img
98
102
103
+ matches , msg = _signature_matches_extension (filename , sniff )
104
+ if not matches :
105
+ raise ImageFileError (msg )
106
+
99
107
raise ImageFileError (f'Cannot work out file type of "{ filename } "' )
100
108
101
109
0 commit comments