Feemarker writing images to html

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-21 12:21:19

问题


is there anyway to write image in freemarker instead of giving link as

<img src="${pathToPortalImage}

Note : cant we use otputstream or something in freemarker ?


回答1:


You can embed the image as base64 directly inside the html img tag.

To convert an image to base 64 you can use Apache Commons (codec).

Here is a solution using Apache Commons IO + Codec (but you can do without if you want):

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;

Then pass the variable imgAsBase64 into the Freemarker context, and use it like this:

<img alt="My image" src="${imgAsBase64}" />



回答2:


A great example above. But with JAVA 8 we can do something like this:

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;


来源:https://stackoverflow.com/questions/13339445/feemarker-writing-images-to-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!