如何序列化包含图像的对象?

How to serialize an object containing an Image?

如何使用 Image 发送对象?我收到此错误:

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

我可以发送普通对象,e。字符串,或任何其他对象。

     public void sentObject(Card GraczK) throws IOException 
     {

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

      }

卡片类型

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;
}

}

How i can sent object with an Image?

您无法序列化 Image。它通常是 "hooked into" 发送者的图形环境,序列化无法处理。

您需要做的是将 img 字段标记为 transient。最终效果是接收方将 null 视为值。如果需要,您可以通过从接收端的 JAR 或 WAR(或其他地方)加载等效的 Image 来(重新)填充该字段。 (这意味着最好为卡片图像包含一个 "name" 以方便图像加载。)

您可以使用自定义 readObject / writeObject 方法来隐藏它,但可能需要对它们进行编码以执行与上述相同的操作......在幕后。

您也可以(我猜)将 Image 像素转换为字节数组,传输它,并在另一端将像素重建为 Image。然而,这会使您发送的 "message" 变得臃肿,而且可能还会出现更多问题。所以我不推荐这个。

您无法序列化图像,只需将该字段标记为瞬态即可。 如果仍然想序列化它,那么替代方法是将另一个字段添加到您的 class

private String imgBase64String; // Image to Base64 String.

将您的图像转换为 Base64 字符串。可以是 serialize/deserialize。并且Base64字符串可以转换回Image。