0

我正在为我的 Android 应用程序开发一个库,我在其中将额外的信息附加到 PNG 图像的末尾。我正在创建一个DataOutputStream变量并将额外的信息写入它的末尾,以便在我打开 PNG 并使用DataInputStream将其转换为位图时使用。我添加了一个标记来区分图像代码何时完成以及我的额外信息何时开始。

标记后正确附加了额外的数据。问题是只读取DataInputStream的 PNG 数据以将其转换为位图。正在读取所有DataInputStream(即使我在标记之前添加了大量占位符字节)。

我用来读取流的 PNG 部分的实现是:

位图图像 = BitmapFactory.decodeStream(inputStream);

我想知道是否有另一种方法我应该实现它以在 PNG 数据字节之后停止读取流。

如果没有更好的方法,我将采取的方法是将输入流复制到数组中。然后我会读取所有数据,直到到达标记。

4

1 回答 1

1

您可以创建一个包装器 InputStream,然后在读取整个流之前报告 EOF。这使您不必将整个流读入字节数组。

class MarkerInputStream extends FilterInputStream {
    MarkerInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        if (isAtMarker()) {
            return -1;
        }
        // may need to read from a cache depending on what isAtMarker method does.
        return super.read();
    }

    private boolean isAtMarker() {
        // logic for determining when you're at the end of the image portion
        return false;
     }
}
于 2013-06-07T17:10:32.970 回答