Display and Save image in JTextPane

287 Views Asked by At

I need to write an Editor like Word. It need to support edit file, insert and remove image and some other things.
I choose JTextPane to do such things.
I load and show image using imageIcon like this way:

BufferedImage img = ImageIO.read(file);
ImageIcon icon = new ImageIcon(img);
insertIcon(new ImageIcon(img));

And the problem I am facing now is how to save the image into file? I use HTMLDocument and HTMLEditorKit to implement the save method, the main logic is as below:

public void saveAs() {
    doc = (HTMLDocument) getStyledDocument();
    File newFile = new File(path);
    FileWriter fw = new FileWriter(newFile);
    kit.write(fw, doc, 0, doc.getLength());
    fw.close();
}

Kit and doc are private members in my Page class (Page derived from JTextPane). And after the saveAs method excuted, the file saved doesn't including the image:

<html>
   <head>

  </head>
   <body>
     <p style="margin-top: 0">
      hello world
     </p>
    <p style="margin-top: 0">
       <p $ename="icon">
    </p>
   </body>
</html>

From the HTML file we can see that the image path are not coded into there, I wonder how can I implement the saveAs method to support saving image?
Thanks a lot!

1

There are 1 best solutions below

0
On

Actually Icon you inserted is not part of HTML so it's not saved. To do it in HTML style you need to insert <IMG> tag with reference to the image URL.

Could be file://... some path here ... yourImage.jpg

If you need to embed image somehow HTMLEditorKit is not enough.

There is no simple way to embed image.

You can see my attempt to do this in RTF

But in general you should write the code yourself.