Skip to Content
Modern Python Standard Library Cookbook
book

Modern Python Standard Library Cookbook

by Alessandro Molina
August 2018
Intermediate to advanced
366 pages
10h 14m
English
Packt Publishing
Content preview from Modern Python Standard Library Cookbook

How to do it...

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Advanced Python Development: Using Powerful Language Features in Real-World Applications

Matthew Wilkes

Publisher Resources

ISBN: 9781788830829Supplemental Content