我的解决方案。在 LG G2 手机上测试。我注意到,当我使用相机拍摄新照片时,一切正常。ExifInterface 返回正确的方向。所以它一定是路径中的东西,因为我的路径在这行代码中为空:
exif = new ExifInterface(path);
但是当我使用绝对路径时,我的应用程序崩溃了。但是解决方法就在下面这个方法中,因为这取决于你的sdk版本。还要注意一点,我只使用绝对路径来选择画廊图片,因为如果我将它用于相机,我的应用程序就会崩溃。我是编程新手,刚刚失去了 2 天的时间来解决这个问题。希望它会帮助某人。
public String getRealPathFromURI(Uri uri) {
if(Build.VERSION.SDK_INT >= 19){
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA };
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
}else{
return null;
}
}else{
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
所以我在 onActivityResult 方法中得到了我的 ExifInterface
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
try {
exif = new ExifInterface(getRealPathFromURI(data.getData()));
} catch (IOException e) {
e.printStackTrace();
}
showImage(data.getData());
} else if (requestCode == CAMERA_IMAGE_REQUEST && resultCode == RESULT_OK) {
try {
exif = new ExifInterface(Uri.fromFile(getCameraFile()).getPath());
} catch (IOException e) {
e.printStackTrace();
}
showImage(Uri.fromFile(getCameraFile()));
}
}
我的显示图像方法看起来像这样
public void showImage(Uri uri) {
if (uri != null) {
try {
Bitmap bitmap = scaleBitmapDown(MediaStore.Images.Media.getBitmap(getContentResolver(), uri), IMAGE_SIZE);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
bitmap = rotateBitmap(bitmap, orientation);
if (whatPlayer.equals("Player1")) {
mImagePlayer1.setImageBitmap(bitmap);
bitmapPlayer1 = bitmap; //*save picture in static variable so other activity can use this
}
if (whatPlayer.equals("Player2")) {
mImagePlayer2.setImageBitmap(bitmap);
bitmapPlayer2 = bitmap;
}
} catch (IOException e) {
Log.d(TAG, "Image picking failed because " + e.getMessage());
Toast.makeText(this, R.string.image_picker_error, Toast.LENGTH_LONG).show();
}
} else {
Log.d(TAG, "Image picker gave us a null image.");
Toast.makeText(this, R.string.image_picker_error, Toast.LENGTH_LONG).show();
}
}