Feemarker将图像写入html

Jan*_*ith 5 java freemarker

无论如何在freemarker中写图像而不是给出链接

<img src="${pathToPortalImage}

注意:我们不能使用otputstream或freemarker中的某些内容?

Ale*_*lex 9

您可以将图像直接嵌入到html img标记内的base64中.

要将图像转换为base 64,您可以使用Apache Commons(编解码器).

这是使用Apache Commons IO + Codec的解决方案(但如果你愿意,你可以不用):

File img = new File("file.png");
byte[] imgBytes = IOUtils.toByteArray(new FileInputStream(img));
byte[] imgBytesAsBase64 = Base64.encodeBase64(imgBytes);
String imgDataAsBase64 = new String(imgBytesAsBase64);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;
Run Code Online (Sandbox Code Playgroud)

然后将变量传递给imgAsBase64Freemarker上下文,并像这样使用它:

<img alt="My image" src="${imgAsBase64}" />
Run Code Online (Sandbox Code Playgroud)