1

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.

Pedro Cimini
  • 175
  • 1
  • 1
  • 7
  • 2
    possible duplicate of [Sending a screenshot (bufferedImage) over a socket in java](http://stackoverflow.com/questions/6973848/sending-a-screenshot-bufferedimage-over-a-socket-in-java) – Kiril Jan 09 '12 at 17:42
  • I didn't find that one while searching, thanks! – Pedro Cimini Jan 09 '12 at 17:44

2 Answers2

4

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).

kan
  • 28,279
  • 7
  • 71
  • 101
  • @Arin It is so many options how it could be implemented... So, it is difficult to come up with a definitive sample. In most situations it's better not to use raw TCP, but use e.g. HTTP: http://stackoverflow.com/questions/2438375/how-to-convert-bufferedimage-to-image-to-display-on-jsp – kan Dec 19 '16 at 10:26
  • @Arin Here is an example with an in-memory storage: http://stackoverflow.com/a/4944536/438742 – kan Dec 19 '16 at 10:33
0

See the ImageIO class which contains methods for reading and writing BufferedImages and RenderedImages to/from various input/output streams.

maerics
  • 151,642
  • 46
  • 269
  • 291