imcrazytwkr

Simple image format detector for images from Tumblr

Apr 13th, 2019
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. from pathlib import Path
  2.  
  3. __all__ = ["detect_format"]
  4.  
  5. def detect_format(file_path):
  6.     if not isinstance(file_path, Path):
  7.         raise TypeError("Image file passed to format detector must be a Path")
  8.  
  9.     with file_path.open("rb") as handler:
  10.         header = handler.read(32)
  11.  
  12.     # JPEG data in JFIF or Exif format
  13.     if header[6:10] in (b"JFIF", b"Exif"):
  14.         return ".jpg"
  15.  
  16.     # GIF-87 and GIF-89
  17.     if header[0:6] in (b"GIF87a", b"GIF89a"):
  18.         return ".gif"
  19.  
  20.     # Regular PNG image
  21.     if header[0:8] == b"\211PNG\r\n\032\n":
  22.         return ".png"
  23.  
  24.     # WebP
  25.     if header[0:4] == b"RIFF" and h[8:12] == b"WEBP":
  26.         return ".webp"
  27.  
  28.     # Couldn't detect anything, falling back to just returning suffix
  29.     return file_path.suffix
Advertisement
Add Comment
Please, Sign In to add comment