If we know what kind of image we are facing, detecting the resolution is usually a matter of reading it from the image header.
For most image types, this is relatively simple, and as we can use imghdr
to guess the right image type, we can then read the right part of the header, according to the detected type, to extract the size portion.
Once imghdr
detects the image type, we can read the content of the header with the struct
module:
import imghdr import struct import os from pathlib import Path class ImageReader: @classmethod def get_size(cls, f): requires_close = False if isinstance(f, (str, getattr(os, 'PathLike', str))): f = open(f, 'rb') requires_close = True elif isinstance(f, Path): f = f.expanduser().open('rb') requires_close = True try: image_type = imghdr.what(f) if image_type not in ('jpeg', 'png', 'gif'): raise...