__all__ = ['MIMEImage']
from email import encoders
from email.mime.nonmultipart import MIMENonMultipart
class MIMEImage(MIMENonMultipart):
def __init__(self, _imagedata, _subtype=None,
_encoder=encoders.encode_base64, *, policy=None, **_params):
_subtype = _what(_imagedata) if _subtype is None else _subtype
if _subtype is None:
raise TypeError('Could not guess image MIME subtype')
MIMENonMultipart.__init__(self, 'image', _subtype, policy=policy,
**_params)
self.set_payload(_imagedata)
_encoder(self)
_rules = []
def _what(data):
for rule in _rules:
if res := rule(data):
return res
else:
return None
def rule(rulefunc):
_rules.append(rulefunc)
return rulefunc
@rule
def _jpeg(h):
if h[6:10] in (b'JFIF', b'Exif'):
return 'jpeg'
elif h[:4] == b'\xff\xd8\xff\xdb':
return 'jpeg'
@rule
def _png(h):
if h.startswith(b'\211PNG\r\n\032\n'):
return 'png'
@rule
def _gif(h):
if h[:6] in (b'GIF87a', b'GIF89a'):
return 'gif'
@rule
def _tiff(h):
if h[:2] in (b'MM', b'II'):
return 'tiff'
@rule
def _rgb(h):
if h.startswith(b'\001\332'):
return 'rgb'
@rule
def _pbm(h):
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'14' and h[2] in b' \t\n\r':
return 'pbm'
@rule
def _pgm(h):
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r':
return 'pgm'
@rule
def _ppm(h):
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'36' and h[2] in b' \t\n\r':
return 'ppm'
@rule
def _rast(h):
if h.startswith(b'\x59\xA6\x6A\x95'):
return 'rast'
@rule
def _xbm(h):
if h.startswith(b'#define '):
return 'xbm'
@rule
def _bmp(h):
if h.startswith(b'BM'):
return 'bmp'
@rule
def _webp(h):
if h.startswith(b'RIFF') and h[8:12] == b'WEBP':
return 'webp'
@rule
def _exr(h):
if h.startswith(b'\x76\x2f\x31\x01'):
return 'exr'