Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitmapFactory.Options returns 0 width and height

Tags:

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;

path is the image file path which is proper.

The problem is options.outHeight and options.outWidth are 0 when the image is captured in Landscape mode with AutoRotate on. If I turn off AutoRotate, it works fine. Since its width and height are 0 I was getting a null Bitmap at the end.

Complete Code:

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);
}
like image 344
Archie.bpgc Avatar asked Nov 19 '13 11:11

Archie.bpgc


1 Answers

I had the same issue, I fixed it by changing :

BitmapFactory.decodeFile(path, options);

to:

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

After that change, the width and height were correctly set.

like image 83
Arnaud Avatar answered Nov 14 '22 05:11

Arnaud