Hello and thank you for your help in advance.
I'm working on an rpg character builder. Each character is stored as a JSON file and I would like to include the character image. This was stored as an ImageIcon, but it can't be stored in a JSON.
How can I convert the ImageIcon to a String and back again?
This is what I have so far:
public ImageIcon getImageIcon() {
byte b[];
ByteArrayInputStream bi;
ObjectInputStream si;
ImageIcon image = null;
try {
b = this.imageIcon.getBytes();
bi = new ByteArrayInputStream(b);
si = new ObjectInputStream(bi);
image = (ImageIcon) si.readObject();
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex);
}
return image;
}
public void setImageIcon(ImageIcon imageIconIn) {
ByteArrayOutputStream bo;
ObjectOutputStream so;
try{
bo = new ByteArrayOutputStream();
so = new ObjectOutputStream(bo);
so.writeObject(imageIconIn);
so.flush();
this.imageIcon = bo.toString();
} catch (IOException ex){
System.out.println(ex);
}
}
The problem is I get the following error when converting the String back to an ImageIcon:
java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
I think the setImageIcon() method is fine, but I'm not sure how to fix the getImageIcon() method.
I'm using Java 1.8 and GSON 2.8.0
Thanks again for your help.