BitmapFactory.Options返回0的宽度和高度

12
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
final int height = options.outHeight;
final int width = options.outWidth;

path是正确的图像文件路径。

问题在于当以横向模式和自动旋转开启时,options.outHeightoptions.outWidth的值为0。如果关闭自动旋转,则可以正常工作。由于其宽度和高度为0,在最后得到一个null Bitmap

完整代码:

Bitmap photo = decodeSampledBitmapFromFile(filePath, DESIRED_WIDTH,
                    DESIRED_HEIGHT);
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth,
            int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    // Calculate inSampleSize, Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    int inSampleSize = 1;

    if (height > reqHeight) {
        inSampleSize = Math.round((float) height / (float) reqHeight);
    }
    int expectedWidth = width / inSampleSize;
    if (expectedWidth > reqWidth) {
        inSampleSize = Math.round((float) width / (float) reqWidth);
    }
    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(path, options);
}

1
我也遇到了同样的问题。你找到任何解决方法了吗? - ARP
1个回答

8

我遇到了同样的问题,我通过更改以下内容来解决它:

BitmapFactory.decodeFile(path, options);

to:

try {
    InputStream in = getContentResolver().openInputStream(
                       Uri.parse(path));
    BitmapFactory.decodeStream(in, null, options);
} catch (FileNotFoundException e) {
  // do something
}

修改后,宽度和高度被正确设置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接