简体   繁体   English

Java - 通过TCP套接字传输BufferedImage

[英]Java - Transferring BufferedImage through TCP Socket

I am not very good in Java, and I need to send a BufferedImage through a TCP socket. 我不是很擅长Java,我需要通过TCP套接字发送BufferedImage。 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. 我已经设法建立连接(并发送字符串),但我无法找到我应该使用哪个Writer来发送和恢复BufferedImage。

You should ImageIO.write to serialize an image as a byte stream using some format (PNG, JPG, etc.). 您应该使用ImageIO.write将图像序列化为使用某种格式(PNG,JPG等)的字节流。

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. 简单的解决方案是将所有内容保存到内存中的字节数组中(使用ByteArrayOutputStream)然后发送它。 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 ,其中包含用于向/从各种输入/输出流读取和写入BufferedImageRenderedImage的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM