Skip to content
Advertisement

Feemarker writing images to html

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 ?

Advertisement

Answer

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}" />
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement