3

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?

Anthony
  • 7,638
  • 3
  • 38
  • 71

1 Answers1

3

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Simple solution - wrap InputStream data with BufferedInputStream always, it will make no harm, even if it is already a BufferedInputStream – Evgeniy Dorofeev Sep 21 '13 at 16:30
  • I've tried that, wrapping if necessary. No matter what I've tried, including your above suggestion, if the underlying stream is a `FileInputStream` it will crash. – Anthony Sep 21 '13 at 16:38
  • 1
    BufferedInputStream buffers your file into memory from the mark onwards. If the file is too big, than it can crash. – Saša Jan 29 '14 at 11:54