3

我分两步解码jpeg。

  1. 检查界限,必要时确定比例。
  2. 在屏幕范围内解码。

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手动重置FileInputStreams位置的部分,但这似乎是一个相当尴尬的解决方案。有没有办法正确重置BufferedInputStream封装的 a FileInputStream

4

1 回答 1

3

在使用 InputStream.reset 之前,您必须先调用 InputStream.mark 来标记您以后要返回的位置。

于 2013-09-21T05:47:47.503 回答