final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
final int height = options.outHeight;
final int width = options.outWidth;
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
我有同样的问题,我修改了它:
BitmapFactory.decodeFile(path, options);
Run Code Online (Sandbox Code Playgroud)
至:
try {
InputStream in = getContentResolver().openInputStream(
Uri.parse(path));
BitmapFactory.decodeStream(in, null, options);
} catch (FileNotFoundException e) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
更改后,正确设置宽度和高度.