我正在尝试创建一个简单地包装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,用于修改内部流位置。
https://stackoverflow.com/questions/53597325
复制相似问题