From 5a484ab1f55d36977e8ed15aefef3daff36d1fb2 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Tue, 8 Jul 2014 11:03:27 +0100 Subject: Extract common image conversion code --- mammoth/__init__.py | 4 +++- mammoth/conversion.py | 12 ++++-------- mammoth/images.py | 9 +++++++++ 3 files changed, 16 insertions(+), 9 deletions(-) create mode 100644 mammoth/images.py (limited to 'mammoth') diff --git a/mammoth/__init__.py b/mammoth/__init__.py index 05e2167..0b524b1 100644 --- a/mammoth/__init__.py +++ b/mammoth/__init__.py @@ -1,5 +1,7 @@ from .results import Result -from . import docx, conversion, options, documents +from . import docx, conversion, options, documents, images + +__all__ = ["convert_to_html", "extract_raw_text", "images"] def convert_to_html(fileobj, transform_document=None, **kwargs): diff --git a/mammoth/conversion.py b/mammoth/conversion.py index 0349774..715e5e0 100644 --- a/mammoth/conversion.py +++ b/mammoth/conversion.py @@ -1,7 +1,7 @@ import base64 import io -from . import documents, results, html_paths +from . import documents, results, html_paths, images from .html_generation import HtmlGenerator, satisfy_html_path @@ -29,7 +29,7 @@ class DocumentConverter(object): documents.Table: self._convert_table, documents.TableRow: self._convert_table_row, documents.TableCell: self._convert_table_cell, - documents.Image: convert_image or self._convert_image, + documents.Image: convert_image or images.inline(self._convert_image), } @@ -99,17 +99,13 @@ class DocumentConverter(object): html_generator.end() - def _convert_image(self, image, html_generator): + def _convert_image(self, image): with image.open() as image_bytes: encoded_src = base64.b64encode(image_bytes.read()).decode("ascii") - attributes = { + return { "src": "data:{0};base64,{1}".format(image.content_type, encoded_src) } - if image.alt_text: - attributes["alt"] = image.alt_text - - html_generator.self_closing("img", attributes) def _convert_elements_to_html(self, elements, html_generator): diff --git a/mammoth/images.py b/mammoth/images.py new file mode 100644 index 0000000..713f739 --- /dev/null +++ b/mammoth/images.py @@ -0,0 +1,9 @@ +def inline(func): + def convert_image(image, html_generator): + attributes = func(image).copy() + if image.alt_text: + attributes["alt"] = image.alt_text + + html_generator.self_closing("img", attributes) + + return convert_image -- cgit v1.2.3