imghdr.py 582 B

12345678910111213141516171819202122
  1. def what(file=None, h=None):
  2. """Detect format of image (Currently supports jpeg, png, webp, gif only)
  3. Ref: https://github.com/python/cpython/blob/3.11/Lib/imghdr.py
  4. Ref: https://www.w3.org/Graphics/JPEG/itu-t81.pdf
  5. """
  6. if h is None:
  7. with open(file, 'rb') as f:
  8. h = f.read(12)
  9. if h.startswith(b'RIFF') and h.startswith(b'WEBP', 8):
  10. return 'webp'
  11. if h.startswith(b'\x89PNG'):
  12. return 'png'
  13. if h.startswith(b'\xFF\xD8\xFF'):
  14. return 'jpeg'
  15. if h.startswith(b'GIF'):
  16. return 'gif'
  17. return None