我正在尝试创建一个简单地包装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,用于修改内部流位置。
发布于 2018-12-04 16:21:10
我也遇到过类似的挑战,我创建了一个在BSD许可下可以在GitHub上使用的implementation。它不是包装一个数组,而是直接使用byte
数组。
我还没有测试你的实现,但我认为它的主要问题是它在读取时没有正确地更新streamPos
。当您调用super.seek(pos)
时,查找似乎还可以。以下操作可以解决此问题:
@Override
public int read() throws IOException {
bitOffset = 0;
int val = stream.read();
if (val != -1) {
streamPos++;
}
return val;
}
@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;
}
int read = stream.read(b, off, len);
if (read > 0) {
streamPos += read;
}
return read;
}
我还认为,严格来说,isCached()
和isCachedMemory
应该为您的实现返回true
,如果它确实由byte
数组支持的话。但我认为这并不重要(即。我从来没有见过真正使用这些方法来优化任何东西的代码)。
https://stackoverflow.com/questions/53597325
复制相似问题