【问题标题】:Correct way to send BufferedImage in object with serialization. writeObject readObject通过序列化在对象中发送 BufferedImage 的正确方法。写对象读对象
【发布时间】:2015-04-25 08:47:44
【问题描述】:

我正在尝试通过套接字发送带有 BufferedImage 的对象。我现在意识到我必须让它瞬态,类实现可序列化,并覆盖 writeObject 和 readObject 方法。我认为我的写作是正确的,但我的阅读我一直给我一个 EOFException。这是我的课:

private void writeObject(ObjectOutputStream out)throws IOException{
    out.defaultWriteObject();
    //write buff with imageIO to out
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", baos);
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException{
    in.defaultReadObject();
    //read buff with imageIO from in
    DataInputStream dis = new DataInputStream(in);

   int len = dis.readInt();

    byte[] data = new byte[len];
    dis.readFully(data);
    dis.close();
    in.close();

    InputStream ian = new ByteArrayInputStream(data);
    image= ImageIO.read(ian);
}

我认为 readObject 中的 readInt() 正在抛出它。

【问题讨论】:

  • 请发布完整的堆栈跟踪。
  • @Turing85 奇怪的是它没有给我一个堆栈跟踪。当我点击它时,Eclipse 说找不到源
  • 我很确定它是 readInt() 虽然

标签: java sockets serialization


【解决方案1】:

您的 writeObject 永远不会写出。它写入以后不使用的 ByteArrayOutputStream

更新 参见例如post 图像列表如何序列化。你可以跳过计数写/读

【讨论】:

  • 会 ImageIO.write(image, "jpg", out);做这份工作?抱歉,我对套接字还不太熟悉。
  • 最后应该将图像字节写出。我认为直接写出来是可以的,但你可以试试
  • 如何获取图像字节?并准确地写出来?
【解决方案2】:

这里的问题是您正在阅读尚未编写的内容。如果您希望读取一个 int,则需要 write 一个 int。相反,您将图像转储到输出流中的字节数组,这对序列化的影响为零。

您的代码没有意义。

如果你写一个图像,把它写到对象流,然后用同样的方法读回来,ImageIO.

注意,如果您遇到异常,则肯定在某处存在堆栈跟踪。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多