从我的库中选择图像时,我无法获得方向。如果我转到图像细节,我可以看到图像方向设置为90度。但是,我的方向始终为0。
String[] orientationColumn = { MediaStore.Images.ImageColumns.ORIENTATION };
Cursor cur = managedQuery(data.getData(), orientationColumn, null, null, null);
int orientation = -1;
if (cur != null && cur.moveToFirst()) {
orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));
}
使用ExitInterface:
ExifInterface exif = new ExifInterface(data.getData().getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION);
两种方式都返回0.我从库启动select活动,如下所示:
protected void selectFromLibrary() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent,
REQUEST_SELECT_IMAGE_FILE);
}
这是在LG G2上运行4.4.2
答案 0 :(得分:5)
我遇到过几个解决方案(比如Images taken with ACTION_IMAGE_CAPTURE always returns 1 for ExifInterface.TAG_ORIENTATION on some newer devices),但没有一个能为我工作。
最终救了我的是这段代码: http://androidxref.com/4.0.4/xref/packages/apps/Gallery2/src/com/android/gallery3d/data/Exif.java
所以,一开始我试图使用默认的exif方法获取方向。当它失败时,我正在释放野兽。 我的完整代码:
protected Matrix getRotationMatrix(String path, String mimeType, Context ctx, Uri imgUri)
{
Matrix mtx = new Matrix();
try {
ExifInterface exif = new ExifInterface(path);
if (mimeType.contains("jpeg") && exif != null) {
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
if (orientation != ExifInterface.ORIENTATION_UNDEFINED) {
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
break;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
mtx.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
mtx.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
mtx.setRotate(180);
mtx.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
mtx.setRotate(90);
mtx.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
mtx.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
mtx.setRotate(-90);
mtx.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
mtx.setRotate(-90);
break;
}
}
else
{
if (ctx != null && imgUri != null)
{
Cursor cursor = ctx.getContentResolver().query(imgUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
null, null, null);
try {
if (cursor.moveToFirst()) {
orientation = cursor.getInt(0);
if (orientation != ExifInterface.ORIENTATION_UNDEFINED)
mtx.postRotate(cursor.getInt(0));
else {
// last try...
mtx.postRotate( Exif.getOrientation(ctx.getContentResolver().openInputStream(imgUri)));
}
}
} finally {
cursor.close();
}
}
}
}
}
catch(Exception ex)
{
return mtx;
}
return mtx;
}
然后我在Bitmap.createBitmap
方法中使用此矩阵以正确的方式旋转图像。