Search code examples
javahtmlswingbase64jeditorpane

JEditorPane html document inline (embedded) image from file


I'm trying to inline (embed) an image in a JEditorPane from a file such as:

<img src="data:image/gif;utf-8,data..."> 

But I'm struggling with the code.

So far I have (assuming a gif file):

try
{
    File imageFile = new File("C:\\test\\testImage.gif"); 
    File htmlFile = new new File("C:\\test\\testOutput.html");

    byte[] imageBytes = Files.toByteArray(imageFile);
    String imageData = new String(imageBytes, "UTF-8");

    String html = "<html><body><img src=\"data:image/gif;utf-8," + imageData + "\"></body></html>";

    FileUtils.writeStringToFile(htmlFile, htmlText);

} catch (Exception e) {
    e.printStackTrace();
}

This does create a file but the image is invalid. I'm sure I'm not converting the image the proper way...


Solution

  • JEditorPane (and Java HTML rendering in general) does not support Base64 encoded images.

    Of course 'does not' != 'could not'.

    The thing is, you'd need to create (or adjust) an EditorKit can have new elements defined. An e.g. is seen in the AppletEditorKit. You'd need to look for HTML.tag.IMG - it is is a standard image, call the super functionality, else use this source (or similar) to convert it to an image, then embed it.