BitmapFactory.Options给出0宽度和高度

时间:2013-11-19 11:24:24

标签: android bitmap

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

路径是适当的图像文件路径。

横向模式下使用 AutoRotate 捕获图像时,问题是 options.outHeight和options.outWidth为0 。如果我关闭 AutoRotate ,它可以正常工作。由于它的宽度和高度都是0,我最后得到一个空位图。

完整代码:

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 个答案:

答案 0 :(得分:7)

我有同样的问题,我通过更改修复了它:

BitmapFactory.decodeFile(path, options);

为:

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

更改后,正确设置了宽度和高度。