image.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (C) 2001-2006 Python Software Foundation
  2. # Author: Barry Warsaw
  3. # Contact: email-sig@python.org
  4. """Class representing image/* type MIME documents."""
  5. __all__ = ['MIMEImage']
  6. import imghdr
  7. from email import encoders
  8. from email.mime.nonmultipart import MIMENonMultipart
  9. class MIMEImage(MIMENonMultipart):
  10. """Class for generating image/* type MIME documents."""
  11. def __init__(self, _imagedata, _subtype=None,
  12. _encoder=encoders.encode_base64, *, policy=None, **_params):
  13. """Create an image/* type MIME document.
  14. _imagedata is a string containing the raw image data. If this data
  15. can be decoded by the standard Python `imghdr' module, then the
  16. subtype will be automatically included in the Content-Type header.
  17. Otherwise, you can specify the specific image subtype via the _subtype
  18. parameter.
  19. _encoder is a function which will perform the actual encoding for
  20. transport of the image data. It takes one argument, which is this
  21. Image instance. It should use get_payload() and set_payload() to
  22. change the payload to the encoded form. It should also add any
  23. Content-Transfer-Encoding or other headers to the message as
  24. necessary. The default encoding is Base64.
  25. Any additional keyword arguments are passed to the base class
  26. constructor, which turns them into parameters on the Content-Type
  27. header.
  28. """
  29. if _subtype is None:
  30. _subtype = imghdr.what(None, _imagedata)
  31. if _subtype is None:
  32. raise TypeError('Could not guess image MIME subtype')
  33. MIMENonMultipart.__init__(self, 'image', _subtype, policy=policy,
  34. **_params)
  35. self.set_payload(_imagedata)
  36. _encoder(self)