| 1 |
# Cover art and other images. |
| 2 |
|
| 3 |
import logging |
| 4 |
|
| 5 |
import filetype |
| 6 |
|
| 7 |
from mediafile.constants import ImageType |
| 8 |
|
| 9 |
log = logging.getLogger(__name__) |
| 10 |
|
| 11 |
|
| 12 |
def image_mime_type(data): |
| 13 |
"""Return the MIME type of the image data (a bytestring).""" |
| 14 |
return filetype.guess_mime(data) |
| 15 |
|
| 16 |
|
| 17 |
def image_extension(data): |
| 18 |
ext = filetype.guess_extension(data) |
| 19 |
# imghdr returned "tiff", so we should keep returning it with filetype. |
| 20 |
return ext if ext != "tif" else "tiff" |
| 21 |
|
| 22 |
|
| 23 |
class Image: |
| 24 |
"""Structure representing image data and metadata that can be |
| 25 |
stored and retrieved from tags. |
| 26 |
|
| 27 |
The structure has four properties. |
| 28 |
* ``data`` The binary data of the image |
| 29 |
* ``desc`` An optional description of the image |
| 30 |
* ``type`` An instance of `ImageType` indicating the kind of image |
| 31 |
* ``mime_type`` Read-only property that contains the mime type of |
| 32 |
the binary data |
| 33 |
""" |
| 34 |
|
| 35 |
def __init__(self, data, desc=None, type=None): |
| 36 |
assert isinstance(data, bytes) |
| 37 |
if desc is not None: |
| 38 |
assert isinstance(desc, str) |
| 39 |
self.data = data |
| 40 |
self.desc = desc |
| 41 |
if isinstance(type, int): |
| 42 |
try: |
| 43 |
type = list(ImageType)[type] |
| 44 |
except IndexError: |
| 45 |
log.debug("ignoring unknown image type index %s", type) |
| 46 |
type = ImageType.other |
| 47 |
self.type = type |
| 48 |
|
| 49 |
@property |
| 50 |
def mime_type(self): |
| 51 |
if self.data: |
| 52 |
return image_mime_type(self.data) |
| 53 |
|
| 54 |
@property |
| 55 |
def type_index(self): |
| 56 |
if self.type is None: |
| 57 |
# This method is used when a tag format requires the type |
| 58 |
# index to be set, so we return "other" as the default value. |
| 59 |
return 0 |
| 60 |
return self.type.value |