1

I have an image stored in a database as a blob. I use JDBC to communicate with the database. The returned data from the database is in a byte[]. How can I display this on a JEditorPane? Do I have to write it to disk and then give that location?

Dula
  • 1,404
  • 1
  • 14
  • 29
  • Use `ImageIO` to write the file out to a local file and the use a file based `URL` to load it through the editor – MadProgrammer Jan 06 '19 at 20:53
  • [How to convert a byte array to a BufferedImage in Java?](https://stackoverflow.com/questions/12705385/how-to-convert-a-byte-to-a-bufferedimage-in-java); [jEditorPane handling local images](https://stackoverflow.com/questions/25839668/jeditorpane-handling-local-images) as starting points – MadProgrammer Jan 06 '19 at 20:54
  • Since I'm dealing with HTML code, I have to give it what HTML understands. It's irrelevant that the image is in memory in Java right? – Dula Jan 06 '19 at 20:58
  • `JEditorPane` won't be able to resolve the image if it's store in memory, there's no way to address it. The image MUST be stored either locally to disk or on a web server accessible to the editor – MadProgrammer Jan 06 '19 at 21:00

1 Answers1

1

Something along the lines of this.

1: First get the blob and convert to an ImageIcon from the resultSet.

Blob blob = resultSet.getBlob(1);
ImageIcon imageIcon = new ImageIcon(
blob.getBytes(1, (int)blob.length()));

2: Prepare to be able to add image icon to the JEditorPane/JTextPane (textpane inherits from JEditorPane), something along the lines of:

StyledDocument doc = textPane.getStyledDocument();
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style iconStyle = doc.addStyle("icon", def);
StyleConstants.setAlignment(iconStyle , StyleConstants.ALIGN_CENTER);
StyleConstants.setIcon(s, imageIcon);
  1. Add icon:

doc.insertString(doc.getLength(), " ", doc.getStyle("icon"));

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
  • Does the format of the image matter here? For example jpg vs png? – Dula Jan 06 '19 at 21:24
  • 1
    As per the ImageIcon documentation , gif, jpg or png. "Creates an ImageIcon from an array of bytes which were read from an image file containing a supported image format, such as GIF, JPEG, or (as of 1.3) PNG." – Mattias Isegran Bergander Jan 06 '19 at 21:41