2012-11-12 36 views
5

反正是有寫圖像中的freemarker而不是給的環節Feemarker寫作圖片的HTML

<img src="${pathToPortalImage}

注:不能,我們使用的FreeMarker otputstream什麼?

+0

freemarker的只是一個模板,圖像是圖像,則必須提供其網址,本地文件URL的任何網頁的URL。 – Ankit

+0

我需要這樣的東西http://www.conandalton.net/2008/10/sending-binary-data-from-freemarker.html – Janith

回答

9

您可以直接在html img標記中將圖像作爲base64嵌入。

要將圖像轉換爲基準64,您可以使用Apache Commons (codec)

下面是使用Apache下議院IO +編解碼器解決方案(但是你可以不用,如果你想這樣做):

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}" /> 
+0

我發送內置的格式作爲郵件的內容,在雷鳥它工作正常,圖像加載正常。但在MS展望圖像不加載 – Janith

+0

你應該知道,「數據」URI方案不支持任何地方。例如IE7不知道它。更新:我看到你剛剛意識到它不適用於Outlook。幸運的是,既然是電子郵件,你可以附上圖片。但是,當然,這不是用FreeMarker完成的,而是用JavaMail API完成的。 – ddekany

+0

它適用於我,tq –

0

上面的一個很好的例子。但隨着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;