【问题标题】:Feemarker writing images to htmlFeemarker 将图像写入 html
【发布时间】:2012-10-31 14:59:37
【问题描述】:

有没有办法在 freemarker 中写图片而不是给链接

<img src="${pathToPortalImage}

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

【问题讨论】:

  • freemarker 只是一个模板,图像是图像,你必须提供它的 URL,或者本地文件 url 的 web url。
  • 我需要这样的东西conandalton.net/2008/10/…

标签: java freemarker


【解决方案1】:

您可以将图片作为base64直接嵌入到html的img标签中。

要将图像转换为 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}" />

【讨论】:

  • 我将构建格式作为邮件内容发送,在 Thunderbird 中它工作正常并且图像加载正常。但在 MS Outlook 中图像未加载
  • 您应该知道并非所有地方都支持“数据”URI 方案。例如 IE7 不知道它。更新:我看到您刚刚意识到它也不适用于 Outlook。幸运的是,由于它是一封电子邮件,您可以附加图片。但当然,这不是通过 FreeMarker 完成的,而是通过 JavaMail API 完成的。
【解决方案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;

【讨论】:

    【解决方案3】:
    private String encodeImage(byte[] imageByteArray, String fileType) {
            return "data:" + fileType + ";base64," + Base64.getEncoder().encodeToString(imageByteArray);
        }
    

    在下面的标签中使用输出

    <img src="[OUTPUT_OF_ABOVE_METHOD]">
    

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多