Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset BufferedInputStream Holding a FileInputStream

I'm decoding a jpeg in two steps.

  1. Check bounds, determine scale if necessary.
  2. Decode within screen limits.

public static Bitmap decodeSampledBitmapFromInputStream(InputStream data, int reqWidth, int reqHeight)
{
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(data, null, options);

    // Calculate inSampleSize
    options.inSampleSize = Util.getExactSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    try {
        // TODO: This works, but is there a better way?
        if (data instanceof FileInputStream)
            ((FileInputStream)data).getChannel().position(0);
        else
            data.reset();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return BitmapFactory.decodeStream(data, null, options);
}

When the underlying stream is a FileInputStream it crashes on reset() with:

java.io.IOException: Mark has been invalidated.

So I added the instanceof section to manually reset the position of FileInputStreams, but this seems like a rather awkward solution. Is there no way to properly reset a BufferedInputStream encapsulating a FileInputStream?

like image 844
Anthony Avatar asked Mar 18 '26 03:03

Anthony


1 Answers

Before using InputStream.reset you have to call InputStream.mark first to mark the position you want to return to later.

like image 165
Evgeniy Dorofeev Avatar answered Mar 19 '26 15:03

Evgeniy Dorofeev