9

无论如何要在freemarker中写入图像而不是提供链接作为

<img src="${pathToPortalImage}

注意:我们不能在 freemarker 中使用 otputstream 或其他东西吗?

4

3 回答 3

14

您可以将图像作为 base64 直接嵌入到 htmlimg标记中。

要将图像转换为 base 64,您可以使用Apache Commons (codec)

这是使用 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;

然后将变量传递imgAsBase64到 Freemarker 上下文中,并像这样使用它:

<img alt="My image" src="${imgAsBase64}" />
于 2012-11-12T07:24:53.410 回答
2

上面的一个很好的例子。但是使用 JAVA 8,我们可以这样做:

Path path = Paths.get("image.png");
byte[] data = Files.readAllBytes(path);
byte[] encoded = Base64.getEncoder().encode(data);
String imgDataAsBase64 = new String(encoded);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;
于 2017-06-13T18:17:41.180 回答
1
private String encodeImage(byte[] imageByteArray, String fileType) {
        return "data:" + fileType + ";base64," + Base64.getEncoder().encodeToString(imageByteArray);
    }

在下面的标签中使用输出

<img src="[OUTPUT_OF_ABOVE_METHOD]">
于 2021-10-27T04:42:40.213 回答