1

I have a network program that sends a stream of BufferedImages through a network using ImageIO.write(..), this is working as intended apart from sometimes the Image received on the other end will just be a series of small black and white squares for a long time, then it will eventually switch back to sending the actual images.

I can't find any help with this anywhere.

I'm using Java version 1.8.0_65, I send the image like so:

BufferedImage capture = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
BufferedImage newImage = new BufferedImage(capture.getWidth(), capture.getHeight(), BufferedImage.TYPE_4BYTE_ABGR_PRE);
newImage.createGraphics().drawImage(capture, 0, 0, newImage.getWidth(), newImage.getHeight(), null);
capture = newImage;
BufferedImage difference = null;
if (lastImage != null) {
    difference = getDifferenceImage(capture, lastImage);
} else {
    difference = capture;
}
long generated = System.currentTimeMillis() - start;
ImageIO.write(difference, "png", socket.getOutputStream());
socket.getOutputStream().flush();
Roman C
  • 49,761
  • 33
  • 66
  • 176
Shaun Wild
  • 1,237
  • 3
  • 17
  • 34
  • 1
    How do you use this API? What is Java version? – Roman C Mar 12 '17 at 19:52
  • @RomanC I updated the question. – Shaun Wild Mar 12 '17 at 20:12
  • 1
    I am not an expert in the PNG format, but from what I know (and [the Wikipedia page](https://en.wikipedia.org/wiki/Portable_Network_Graphics) seems to confirm this), there is no way for an image reader to know when the final “chunk” of a PNG image is encountered. You will need to tell the client side how much to read; one way is to write your image to a byte array, then write an int to the socket indicating the byte count, then write the bytes themselves to the socket. – VGR Mar 12 '17 at 20:47

1 Answers1

0

Try this code:

public byte[] getCustomImageInBytes(BufferedImage originalImage) {
    byte[] imageInByte = null;
    try {
        // convert BufferedImage to byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(originalImage, "png", baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return imageInByte;
}

socket.getOutputStream().write(getCustomImageInBytes(difference));
socket.getOutputStream().flush();
Roman C
  • 49,761
  • 33
  • 66
  • 176