从我的库中选择图像时,我无法获取方向。如果我转到图像详细信息,我可以看到图像方向设置为 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]));
}
使用退出接口(interface):
ExifInterface exif = new ExifInterface(data.getData().getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION);
两种方式都返回 0。我像这样启动“从库中选择” Activity :
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);
}
这是在运行 4.4.2 的 LG G2 上
最佳答案
我遇到了几个解决方案(例如这里 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 方法中使用这个矩阵来以正确的方式旋转图像。
关于android - 从库上传图像时无法获取方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24270211/