Determine image type using magic numbers

# -*- coding: utf-8 -*-

# Only required for example usage, see below.
from __future__ import with_statement


MAGIC_NUMBERS = (
    ('gif', '\x47\x49\x46\x38\x37\x61'),  # GIF87a
    ('gif', '\x47\x49\x46\x38\x39\x61'),  # GIF89a
    ('jpeg', '\xFF\xD8\xFF'),
    ('png', '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a'),
    )
MAX_BYTES = max(len(bytes) for name, bytes in MAGIC_NUMBERS)

def guess_image_type(data):
    """Try to determine the image type using `magic numbers`_.

    If the type cannot be determined, ``None`` is returned.

    .. _magic numbers:  http://en.wikipedia.org/wiki/Magic_number_%28programming%29
    """
    if not isinstance(data, basestring):
        data = data.read(MAX_BYTES)
    for type_, magic_number in MAGIC_NUMBERS:
        if data.startswith(magic_number):
            return type_

# example usage:
with open('someimage.jpg', 'rb') as f:
    print guess_image_type(f)