Dula
Dula

Reputation: 1436

JEditorPane show image stored in byte[]

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?

Upvotes: 1

Views: 210

Answers (1)

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

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"));

Upvotes: 1

Related Questions