我分两步解码jpeg。
- 检查界限,必要时确定比例。
- 在屏幕范围内解码。
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);
}
当底层流是 FileInputStream 时,它会崩溃reset()
:
java.io.IOException:标记已失效。
所以我添加了instanceof
手动重置FileInputStream
s位置的部分,但这似乎是一个相当尴尬的解决方案。有没有办法正确重置BufferedInputStream
封装的 a FileInputStream
?