顾名思义,我试图将包含一些BufferedImages(包括其他变量,字符串等)的对象保存到文件中。
我发现了这一点:如何序列化包含BufferedImages的对象
它的工作原理就像一种魅力,但有一点挫折:如果您的对象仅包含一个图像,它就可以很好地工作。
我一直在努力获取他的解决方案以处理多个图像(理论上应该可以使用),但是每次读入文件时,我都会得到对象,图像的数量是正确的,但只有第一个图像实际上被读入;其他只是空图像,其中没有数据。
这是我的对象的样子:
class Obj implements Serializable
{
transient List<BufferedImage> imageSelection= new ArrayList<BufferedImage>();
// ... other vars and functions
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(imageSelection.size()); // how many images are serialized?
for (BufferedImage eachImage : imageSelection) {
ImageIO.write(eachImage, "jpg", out); // png is lossless
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
final int imageCount = in.readInt();
imageSelection = new ArrayList<BufferedImage>(imageCount);
for (int i=0; i<imageCount; i++) {
imageSelection.add(ImageIO.read(in));
}
}
}
这就是我在文件中读写对象的方式:
// writing
try (
FileOutputStream file = new FileOutputStream(objName+".ser");
ObjectOutputStream output = new ObjectOutputStream(file);
){
output.writeObject(myObjs);
}
catch(IOException ex){
ex.printStackTrace();
}
// reading
try(
FileInputStream inputStr = new FileInputStream(file.getAbsolutePath());
ObjectInputStream input = new ObjectInputStream (inputStr);
)
{myObjs = (List<Obj>)input.readObject();}
catch(Exception ex)
{ex.printStackTrace();}
即使我有一个对象列表,也可以正确地读取它们,并且除BufferedImages外,列表中的每个元素均已相应填充。
有人有解决此问题的方法吗?
问题可能是ImageIO.read(...)
在读取第一个图像后错误地定位了流。
我看到两个解决方案:
重写的序列化,BufferedImage
以写入图像,高度,宽度,颜色模型/颜色空间标识符以及其他重新创建所需的数据的后备数组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)));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句