aboutsummaryrefslogtreecommitdiff
path: root/mammoth/images.py
blob: 1623a733a1e8af1e3007c57c0e006dd38dcb8188 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import base64
import re

from . import html


def img_element(func):
    def convert_image(image):
        attributes = {}
        if image.alt_text:
            attributes["alt"] = image.alt_text
        attributes.update(func(image))

        return [html.element("img", attributes)]

    return convert_image

# Undocumented, but retained for backwards-compatibility with 0.3.x
inline = img_element


@img_element
def data_uri(image):
    with image.open() as image_bytes:
        encoded_src = base64.b64encode(image_bytes.read()).decode("ascii")

    return {
        "src": "data:{0};base64,{1}".format(image.content_type, encoded_src)
    }


def image_filename_extension(image):
    result = re.split(r"/|\\", image.content_type)
    if len(result) < 2:
        return None
    else:
        return result[1]