【问题标题】:Reset BufferedInputStream Holding a FileInputStream重置 BufferedInputStream 持有 FileInputStream
【发布时间】:2013-09-21 13:47:47
【问题描述】:

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

【问题讨论】:

    标签: java android fileinputstream bufferedinputstream


    【解决方案1】:

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

    【讨论】:

    • 简单的解决方案 - 始终使用 BufferedInputStream 包装 InputStream 数据,即使它已经是 BufferedInputStream 也不会造成任何伤害
    • 我已经试过了,如果需要的话,可以换行。无论我尝试过什么,包括您的上述建议,如果底层流是FileInputStream,它都会崩溃。
    • BufferedInputStream 从标记开始将您的文件缓冲到内存中。如果文件太大,可能会崩溃。
    猜你喜欢
    • 2016-02-07
    • 2020-11-30
    • 2017-09-21
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2014-10-25
    • 2016-02-18
    • 1970-01-01
    相关资源
    最近更新 更多