Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pathlib import Path
- __all__ = ["detect_format"]
- def detect_format(file_path):
- if not isinstance(file_path, Path):
- raise TypeError("Image file passed to format detector must be a Path")
- with file_path.open("rb") as handler:
- header = handler.read(32)
- # JPEG data in JFIF or Exif format
- if header[6:10] in (b"JFIF", b"Exif"):
- return ".jpg"
- # GIF-87 and GIF-89
- if header[0:6] in (b"GIF87a", b"GIF89a"):
- return ".gif"
- # Regular PNG image
- if header[0:8] == b"\211PNG\r\n\032\n":
- return ".png"
- # WebP
- if header[0:4] == b"RIFF" and h[8:12] == b"WEBP":
- return ".webp"
- # Couldn't detect anything, falling back to just returning suffix
- return file_path.suffix
Advertisement
Add Comment
Please, Sign In to add comment