首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >包装byte[]的ImageInputStreamImpl实现

包装byte[]的ImageInputStreamImpl实现
EN

Stack Overflow用户
提问于 2018-12-03 23:55:52
回答 1查看 51关注 0票数 1

我正在尝试创建一个简单地包装byte[]的ImageInputStream实现。

这是我的实现,但对于某些图像,ImageIO会返回有关损坏数据的错误。

我找不到任何有用的替代方案,与JDK捆绑在一起的ImageInputStreamImpl的每个子类都执行缓存并浪费内存。

public static class MyMemoryCacheImageInputStream extends ImageInputStreamImpl {

        private SimpleByteArrayInputStream stream;

        public MyMemoryCacheImageInputStream(SimpleByteArrayInputStream stream) {
            if (stream == null) {
                throw new IllegalArgumentException("stream == null!");
            }
            this.stream = stream;
        }

        @Override
        public int read() throws IOException {
            bitOffset = 0;
            return stream.read();
        }

        @Override
        public void seek(long pos) throws IOException {
            super.seek(pos);
            stream.seek(pos);
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            if (b == null) {
                throw new NullPointerException("b == null!");
            }
            if (off < 0 || len < 0 || off + len > b.length || off + len < 0) {
                throw new IndexOutOfBoundsException("off < 0 || len < 0 || off+len > b.length || off+len < 0!");
            }

            bitOffset = 0;

            if (len == 0) {
                return 0;
            }

            return stream.read(b, off, len);
        }

        @Override
        public boolean isCached() {
            return false;
        }

        @Override
        public boolean isCachedFile() {
            return false;
        }

        @Override
        public boolean isCachedMemory() {
            return false;
        }

        @Override
        public void close() throws IOException {
            super.close();
            stream = null;
        }
    }

请注意,SimpleByteArrayInputStream本质上是一个带有"seek“方法的ByteArrayInputStream,用于修改内部流位置。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53597325

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档