问题可能是
ImageIO.read(...)在读取第一个图像后错误地定位了流。
我看到两个解决方案:
重写
BufferedImage
s 的序列化,以写入图像,高度,宽度,颜色模型/颜色空间标识符以及其他重新创建所需数据的支持数组BufferedImage
。这需要一些代码才能正确处理各种图像,因此,我现在将略过其细节。可能更快,更准确(但可能会发送更多数据)。继续使用进行序列化
ImageIO
,但使用缓冲每个写入ByteArrayOutputStream
,并在每个映像之前添加其字节数。回读时,首先读取字节数,并确保完全读取每个图像。这实现起来很简单,但是由于文件格式的限制,某些图像可能会转换或丢失细节(即JPEG压缩)。就像是:private void writeObject(ObjectOutputStream out) throws IOException {out.defaultWriteObject();out.writeInt(imageSelection.size()); // how many images are serialized?for (BufferedImage eachImage : imageSelection) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ImageIO.write(eachImage, "jpg", buffer); out.writeInt(buffer.size()); // Prepend image with byte count buffer.writeTo(out); // Write image}}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();int imageCount = in.readInt();imageSelection = new ArrayList<BufferedImage>(imageCount);for (int i = 0; i < imageCount; i++) { int size = in.readInt(); // Read byte count byte[] buffer = new byte[size]; in.readFully(buffer); // Make sure you read all bytes of the image imageSelection.add(ImageIO.read(new ByteArrayInputStream(buffer)));}}



