aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--mammoth/conversion.py15
-rw-r--r--tests/conversion_tests.py9
2 files changed, 24 insertions, 0 deletions
diff --git a/mammoth/conversion.py b/mammoth/conversion.py
index 72867c5..5580925 100644
--- a/mammoth/conversion.py
+++ b/mammoth/conversion.py
@@ -1,3 +1,6 @@
+import base64
+import io
+
from . import documents, results, html_paths
from .html_generation import HtmlGenerator, satisfy_html_path
@@ -23,6 +26,7 @@ class DocumentConverter(object):
documents.Text: self._convert_text,
documents.Hyperlink: self._convert_hyperlink,
documents.Tab: self._convert_tab,
+ documents.Image: self._convert_image,
}
@@ -66,6 +70,17 @@ class DocumentConverter(object):
def _convert_tab(self, tab, html_generator):
html_generator.text("\t")
+
+
+ def _convert_image(self, image, html_generator):
+ with image.open() as image_bytes:
+ output = io.BytesIO()
+ base64.encode(image_bytes, output)
+ encoded_src = output.getvalue().rstrip("\n")
+
+ html_generator.self_closing("img", {
+ "src": "data:{0};base64,{1}".format(image.content_type, encoded_src)
+ })
def _convert_elements_to_html(self, elements, html_generator):
diff --git a/tests/conversion_tests.py b/tests/conversion_tests.py
index 7dc8b06..8935bb5 100644
--- a/tests/conversion_tests.py
+++ b/tests/conversion_tests.py
@@ -1,3 +1,5 @@
+import io
+
from nose.tools import istest, assert_equal
from mammoth import documents, style_reader, results
@@ -115,5 +117,12 @@ def docx_tab_is_converted_to_tab_in_html():
assert_equal('\t', result.value)
+@istest
+def images_are_converted_to_img_tags_with_data_uri():
+ image = documents.image(alt_text=None, content_type="image/png", open=lambda: io.BytesIO("abc"))
+ result = convert_document_element_to_html(image)
+ assert_equal('<img src="data:image/png;base64,YWJj" />', result.value)
+
+
def _run_with_text(text):
return documents.run(children=[documents.text(text)])