2

How i can sent object with Image? I am getting this error:

java.io.NotSerializableException: org.eclipse.swt.graphics.Image 

I can sent normal object, e. String, or whatever other objects.

     public void sentObject(Card GraczK) throws IOException 
     {

            outt.writeObject(GraczK);
            outt.flush();
            System.out.print(GraczK);

      }

CARD type

public class Card implements Serializable {
private int Value, Colour;

private Image img;

public Card(int i, int j) {
    Colour = i;
    Value = j;
    img = new Image(null, MainWarSever.class.getResourceAsStream("/Karty/k" + Value + " (" + Colour + ").png"));
}

public int getValue() {
    return Value;
}

public int getColour() {
    return Colour;
}

public Image getImg() {
    return img;
}

}

user207421
  • 305,947
  • 44
  • 307
  • 483
Pekus
  • 155
  • 1
  • 6
  • 12

2 Answers2

4

How i can sent object with an Image?

You can't serialize an Image. It is typically "hooked into" the sender's graphics environment in ways that serialization is not able to deal with.

What you need to do is to mark the img field as transient. The net effect will be that the receiver sees null as the value. If you need to, you can then (re-)populate the field by loading an equivalent Image from a JAR or WAR (or somewhere else) on the receiving end. (This implies that it would be a good idea to include a "name" for the card's image to facilitate the image load.)

You could use custom readObject / writeObject methods to hide this, but they probably need to be coded to do the same as the above ... under the hood.

You could also (I guess) turn the Image pixels into a byte array, transmit that, and reconstruct the pixels into an Image at the other end. However that is going to bloat the "message" you are sending, and there may be further problems. So I wouldn't recommend this.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

You cannot serialize an Image, just mark that field transient. If still want to serialize it, then alternative is add another field to your class

private String imgBase64String; // Image to Base64 String.

convert your image into Base64 String. It can be serialize/deserialize. And Base64 String can convert back to Image.

Noor Nawaz
  • 2,175
  • 27
  • 36