0
ImageIO.write(image, "png", socket.getInputStream);

This is the only way I tried, and it does work but it needs the outputStream to be closed or I can't save the image.

My problem is that I need the connection to be alive even after the sending, so I read on the internet that i have to convert a BufferedImage in byte[] and viceversa in the client and in the server.

How do I do that?

enemy
  • 101
  • 1
  • 1
  • 3
  • Why does it need the output stream to be closed to save the image? Are you reading until EOF on the other side of the Socket? – Brett Okken Aug 03 '14 at 12:37
  • Because with that command you just read from the InputStream, it doesn't recognize the EOF.. – enemy Aug 03 '14 at 13:31

1 Answers1

0

To quote this answer here.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();

InputStream in = new ByteArrayInputStream(imageInByte); //convert to buffered image
BufferedImage bImageFromConvert = ImageIO.read(in);
Community
  • 1
  • 1
  • And how do i read from that? I need to convert it back – enemy Aug 03 '14 at 13:30
  • @enemy InputStream in = new ByteArrayInputStream(bytes); BufferedImage bImageFromConvert = ImageIO.read(in); – user3902960 Aug 03 '14 at 22:18
  • ByteArrayOutputStream.flush() and .close() do nothing, but if they didn't you would need to call close() before toByteArray(), and the flush would still be redundant. – user207421 Aug 03 '14 at 23:52
  • @user3902960 what is "bytes"? could you write the entire code? I have to read it from another project, so i don't have "bytes" defined. Thank you. – enemy Aug 04 '14 at 13:48