从InputStream调整位图大小

kav*_*ain 5 android bitmap resize-image

我试图从InputStream调整一个图像的大小,所以我在将图像加载到Bitmap对象时使用Strange内存中的代码问题,但我不知道为什么这个代码总是返回没有图像的Drawable.

这个很好用:

private Drawable decodeFile(InputStream f){
    try {
        InputStream in2 = new BufferedInputStream(f);
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=2;
        return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
    } catch (Exception e) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

这个不起作用:

private Drawable decodeFile(InputStream f){
    try {
        InputStream in1 = new BufferedInputStream(f);
        InputStream in2 = new BufferedInputStream(f);
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in1,null,o);

        //The new size we want to scale to
        final int IMAGE_MAX_SIZE=90;

        //Find the correct scale value. It should be the power of 2.
        int scale = 2;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / 
               (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inJustDecodeBounds = false;
        o2.inSampleSize=scale;
        return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
    } catch (Exception e) {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么一个选项影响另一个?如果我使用两个不同的InputStream和Options,它怎么可能?

And*_*ich 8

实际上你有两个不同,BufferedInputStream但它们内部只使用一个InputStream对象,因为BufferedInputStream它只是一个包装器InputStream.

所以你不能只BitmapFactory.decodeStream在同一个流上调用两次方法,它肯定会失败,因为第二次它不会从流的开头开始解码.如果您的流受支持或重新打开,则需要重置该流.

  • 你意识到你正在调整位图的大小以改善内存吗?但是这个链接会让你在内存中保存整个Bitmap的后备字节数组两次......我只是重新打开FileInputStream或者你再次使用它. (2认同)