简体   繁体   English

从输入流读取

[英]Reading from input stream

I am developing a library for my Android application where I am appending extra info to the end of a PNG image. 我正在为Android应用程序开发一个库,在该库中我将附加信息附加到PNG图像的末尾。 I am creating a DataOutputStream variable and writing extra info to the end of it to use when I open the PNG and convert it to a Bitmap using a DataInputStream . 我正在创建一个DataOutputStream变量,并在它的末尾写入额外的信息,以便在我打开PNG并使用DataInputStream将其转换为Bitmap时使用。 I added a marker to distinguish when the image code finishes and my extra info starts. 我添加了一个标记来区分图像代码何时结束以及我的额外信息何时开始。

The extra data is correctly being appended after the marker. 多余的数据正确地附加在标记后面。 The problem is reading ONLY the PNG data of the DataInputStream to convert it into a Bitmap. 问题是读取DataInputStream的PNG数据以将其转换为位图。 All of the DataInputStream is being read (even if I add a large amount of placeholder bytes before the marker). 正在读取所有DataInputStream (即使我在标记之前添加了大量占位符字节)。

The implementation I am using to read the PNG portion of the stream is: 我用来读取流的PNG部分的实现是:

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

I am wondering if there is another way I should be implementing this to stop reading the stream after the PNG data bytes. 我想知道是否还有另一种方法可以实现此目的,以便在PNG数据字节之后停止读取流。

If there isn't a better way, the route I would be taking is copying the input stream into an array. 如果没有更好的方法,我将采取的路线是将输入流复制到数组中。 I would then read all of the data until I reach the marker. 然后,我将读取所有数据,直到到达标记。

You can create a wrapper InputStream that would then report EOF before reading the entire stream. 您可以创建包装器InputStream,然后在读取整个流之前先报告EOF。 This lets you avoid having to read the whole stream into a byte array. 这使您避免必须将整个流读入一个字节数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM