Java - 通过 TCP Socket 传输 BufferedImage
我不太擅长Java,我需要通过TCP套接字发送BufferedImage。我已经成功建立连接(并发送字符串),但我无法真正找到应该使用哪个 Writer 来发送和恢复 BufferedImage。
I am not very good in Java, and I need to send a BufferedImage through a TCP socket. I already managed to make a connection (and send strings), but I couldn't really find out which Writer I should use in order to send and recover the BufferedImage.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该
ImageIO.write
使用某种格式(PNG、JPG 等)将图像序列化为字节流。然后您应该通过线路发送字节流。这里的困难是你不知道前面的流有多大。简单的解决方案是将所有内容保存到内存字节数组中(使用 ByteArrayOutputStream )然后发送它。或者,如果它不适合内存,您应该做一些聪明的事情(将其保存到临时文件中,或使用一些分块协议或发送唯一的终止符标记)。
You should
ImageIO.write
to serialize an image as a byte stream using some format (PNG, JPG, etc.).Then you should send the byte stream over wire. The difficulty here is you don't know the size of the stream ahead. Simple solution is save all content into in-memory byte array (use ByteArrayOutputStream for it) then send it. Or if it doesn't fit into memory you should do something smart (save it into temporary file, or use some chunked protocol or send unique terminator mark).
请参阅
ImageIO
类 其中包含 阅读和编写BufferedImage
和RenderedImage
到/来自各种输入/输出流。See the
ImageIO
class which contains methods for reading and writingBufferedImage
s andRenderedImage
s to/from various input/output streams.