From a82d898bc1c6901749f89a905e63c9e511baae84 Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 14 Feb 2016 12:58:58 +0000 Subject: Include alt text for images if available --- src/main/java/org/zwobble/mammoth/DocumentConverter.java | 9 ++++++++- .../java/org/zwobble/mammoth/html/HtmlSelfClosingElement.java | 4 ++++ 2 files changed, 12 insertions(+), 1 deletion(-) (limited to 'src/main') diff --git a/src/main/java/org/zwobble/mammoth/DocumentConverter.java b/src/main/java/org/zwobble/mammoth/DocumentConverter.java index da10324..f4c15b3 100644 --- a/src/main/java/org/zwobble/mammoth/DocumentConverter.java +++ b/src/main/java/org/zwobble/mammoth/DocumentConverter.java @@ -1,5 +1,6 @@ package org.zwobble.mammoth; +import com.google.common.collect.ImmutableMap; import com.google.common.io.ByteStreams; import org.zwobble.mammoth.documents.*; import org.zwobble.mammoth.html.Html; @@ -134,9 +135,15 @@ public class DocumentConverter { return image.getContentType() .map(contentType -> { try { + ImmutableMap.Builder attributes = ImmutableMap.builder(); + String base64 = Base64.getEncoder().encodeToString(ByteStreams.toByteArray(image.open())); String src = "data:" + contentType + ";base64," + base64; - return list(Html.selfClosingElement("img", map("src", src))); + attributes.put("src", src); + + image.getAltText().ifPresent(altText -> attributes.put("alt", altText)); + + return list(Html.selfClosingElement("img", attributes.build())); } catch (IOException exception) { // TODO: return a result with a warning throw new RuntimeException(exception); diff --git a/src/main/java/org/zwobble/mammoth/html/HtmlSelfClosingElement.java b/src/main/java/org/zwobble/mammoth/html/HtmlSelfClosingElement.java index 73f4734..f8bea1d 100644 --- a/src/main/java/org/zwobble/mammoth/html/HtmlSelfClosingElement.java +++ b/src/main/java/org/zwobble/mammoth/html/HtmlSelfClosingElement.java @@ -11,6 +11,10 @@ public class HtmlSelfClosingElement implements HtmlNode { this.attributes = attributes; } + public Map getAttributes() { + return attributes; + } + @Override public void write(StringBuilder builder) { builder.append("<").append(tagName); -- cgit v1.2.3