无论如何要在freemarker中写入图像而不是提供链接作为
<img src="${pathToPortalImage}
注意:我们不能在 freemarker 中使用 otputstream 或其他东西吗?
无论如何要在freemarker中写入图像而不是提供链接作为
<img src="${pathToPortalImage}
注意:我们不能在 freemarker 中使用 otputstream 或其他东西吗?
您可以将图像作为 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}" />
上面的一个很好的例子。但是使用 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;
private String encodeImage(byte[] imageByteArray, String fileType) {
return "data:" + fileType + ";base64," + Base64.getEncoder().encodeToString(imageByteArray);
}
在下面的标签中使用输出
<img src="[OUTPUT_OF_ABOVE_METHOD]">