栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

序列化包含BufferedImages的对象

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

序列化包含BufferedImages的对象

问题可能是

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)));}

    }



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610169.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号