August 2018
Intermediate to advanced
366 pages
10h 14m
English
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 ValueError('Unsupported image format') f.seek(0) size_reader = getattr(cls, '_size_{}'.format(image_type)) return size_reader(f) finally: if requires_close: f.close() @classmethod def _size_gif(cls, f): f.read(6) # Skip the Magick Numbers ...