Mads Mobæk
Mads Mobæk

Reputation: 35990

Display local image (BufferedImage?) inside JTextPane

I'm trying to display a local image in package1/package2/myImage.gif in a JTextPane. I first tried to load the resource into a BufferedImage:

BufferedImage image = ImageIO.read(ClassLoader.getSystemResourceAsStream(
    "package1/package2/myImage.gif"));

But then I didn't know how to use that in the setText method, so I tried just pointing to the image in a img-tag instead:

textpane.setText("Some text <img src=\"package1/package2/myImage.gif\" />," +
    " and some more text");

This diplay a broken image when run. I'm pretty sure the path is correct, since loading it into the BufferedImage works.

How can I use local resources like the image, along with other text, in a HTML-enabled JTextPane?

Upvotes: 0

Views: 2666

Answers (3)

Arun Kumar S
Arun Kumar S

Reputation: 144

textpane.insertIcon( new ImageIcon( image ) );

Upvotes: 0

Martijn Courteaux
Martijn Courteaux

Reputation: 68907

The image is inside jour application jar. So you have to extract them to a temp file.

public String getImagePath(BufferedImage bi) {
    try {
        File temp = File.createTempFile("image", ".png");
        ImageIO.write(bi, "PNG", new FileOutputStream(temp));
        return temp.getAbsolutePath();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return null;
}

So you can use:

textPane.setText("<html>Some text <img src=\"" + getImagePath(yourLoadedImage) + "\">Some other text");

Upvotes: 1

St.Shadow
St.Shadow

Reputation: 1842

Do you check sun`s tutorial?

Upvotes: 1

Related Questions