android – BitmapFactory.Options给出0宽度和高度

前端之家收集整理的这篇文章主要介绍了android – BitmapFactory.Options给出0宽度和高度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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.outHeight和options.outWidth在横向模式下以AutoRotate打开时捕获图像时为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);
}

解决方法

我有同样的问题,我修改了它:
BitmapFactory.decodeFile(path,options);

至:

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

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

猜你在找的Android相关文章