tags:

views:

167

answers:

2

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?

+1  A: 

Do you check sun`s tutorial?

St.Shadow
A: 

Hi,

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