9

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 ?

Janith
  • 355
  • 1
  • 4
  • 8
  • freemarker is just a template, and image being image, you will have to provide its URL, either web url of local file url. – Ankit Nov 12 '12 at 06:56
  • I need something like this http://www.conandalton.net/2008/10/sending-binary-data-from-freemarker.html – Janith Nov 12 '12 at 07:05

3 Answers3

14

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}" />
Alex
  • 25,147
  • 6
  • 59
  • 55
  • 1
    I m sending built format as content of mail , in Thunderbird it is working fine and image is loading fine. But in MS outlook image is not loading – Janith Nov 12 '12 at 09:20
  • You should know that "data" URI scheme isn't supported everywhere. For example IE7 doesn't know it. Update: I see you have just realized it doesn't work with Outlook either. Luckily, since it's an email, you can attach the images. But of course, that's not done with FreeMarker but with the JavaMail API. – ddekany Nov 12 '12 at 09:24
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;
Greg
  • 1,690
  • 4
  • 26
  • 52
1
private String encodeImage(byte[] imageByteArray, String fileType) {
        return "data:" + fileType + ";base64," + Base64.getEncoder().encodeToString(imageByteArray);
    }

use output in below tag

<img src="[OUTPUT_OF_ABOVE_METHOD]">
Big Bansal
  • 73
  • 2
  • 7