I'm decoding a jpeg in two steps.
- Check bounds, determine scale if necessary.
- 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 FileInputStream
s, but this seems like a rather awkward solution. Is there no way to properly reset a BufferedInputStream
encapsulating a FileInputStream
?