I think this is a known issue.
There's no guarantee that the ImageReader
will read as many bytes as the ImageWriter
originally wrote. It will read as many bytes as needed to efficiently decode (due to buffering, this might be more than the writer wrote, as the stream just continues). This might lead to the stream being "mis-aligned", and the next read(s) will fail.
The workaround is to buffer each write, then write the length (byte count) for each image, before the actual image bytes, or simply write the buffered byte arrays.
When reading back, make sure you have consumed exactly as many bytes as you wrote, by reading or skipping the necessary number of extra bytes.
To write, you can use code similar to:
BufferedImage image = null; // your image
ByteArrayOutputStream bufferStream = new ByteArrayOutputStream();
ImageIO.write(image, "JPEG", bufferStream);
byte[] bufferedBytes = bufferStream.toByteArray();
// Write bufferedBytes to ObjectOutputStream as Object, OR write bufferedBytes.length + bufferedBytes as raw bytes
To read:
byte[] bytes = ...; // from ObjectInputStream
BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));