2020from .deprecated import deprecate_with_version
2121
2222
23- def _signature_matches_extension (filename ):
23+ def _signature_matches_extension (filename , sniff ):
2424 """Check if signature aka magic number matches filename extension.
2525
2626 Parameters
2727 ----------
2828 filename : str or os.PathLike
2929 Path to the file to check
3030
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+
3135 Returns
3236 -------
3337 matches : bool
@@ -50,11 +54,14 @@ def _signature_matches_extension(filename):
5054 if ext not in signatures :
5155 return True , ""
5256 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 } "
5865 if found_signature == expected_signature :
5966 return True , ""
6067 format_name = signatures [ext ]["format_name" ]
@@ -85,9 +92,6 @@ def load(filename, **kwargs):
8592 raise FileNotFoundError (f"No such file or no access: '{ filename } '" )
8693 if stat_result .st_size <= 0 :
8794 raise ImageFileError (f"Empty file: '{ filename } '" )
88- matches , msg = _signature_matches_extension (filename )
89- if not matches :
90- raise ImageFileError (msg )
9195
9296 sniff = None
9397 for image_klass in all_image_classes :
@@ -96,6 +100,10 @@ def load(filename, **kwargs):
96100 img = image_klass .from_filename (filename , ** kwargs )
97101 return img
98102
103+ matches , msg = _signature_matches_extension (filename , sniff )
104+ if not matches :
105+ raise ImageFileError (msg )
106+
99107 raise ImageFileError (f'Cannot work out file type of "{ filename } "' )
100108
101109
0 commit comments