使用EXIF或光标的图像方向始终为0

时间:2012-11-03 09:08:26

标签: android-camera android-orientation android-cursor

我正在从我的肖像相机应用程序拍照并发送到服务器。在发送之前我需要旋转图像,如果有必要。所以我将图像保存在SD卡中并试图获取Exif或Cursor。我经历了大部分帖子与此相关。但没有什么对我有用。这就是代码......

  1. ExifInterface

     File imageFile = new File(uri.toString());
    ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,   ExifInterface.ORIENTATION_NORMAL);
    

    此处任何图像的方向始终为0

  2. Cusor

    int orientation = 0;
    final String[] projection = new String[] { MediaStore.Images.Media.ORIENTATION };
    final Cursor cursor = getApplicationContext()
                    .getContentResolver().query(uri, projection, null,
                            null, null); 
    if (cursor != null) {
    final int orientationColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.ORIENTATION);
    if (cursor.moveToFirst()) {
       orientation = cursor.isNull(orientationColumnIndex) ? 0 : cursor.getInt(orientationColumnIndex);
     }
    

    此处图像旋转也为零。如何找到图像的精确旋转?任何帮助将不胜感激..

1 个答案:

答案 0 :(得分:0)

请从支持库开始使用ExifInterface。它提供了一个支持InputStream的构造函数。从Uri获取路径是错误的。 你需要这个库:在你的build.gradle中编译'com.android.support:exifinterface:25.3.1'。 代码

private float getOrientation (InputStream image, Uri photoURI) {
    //ExifInterface myExif = new ExifInterface(photoURI.getPath());

    float photoRotation = 0;
    boolean hasRotation = true;

    try {
        ExifInterface exif = new ExifInterface(image);
        int exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        switch (exifRotation) {
            case ExifInterface.ORIENTATION_UNDEFINED: {
                hasRotation = false;
            }
            case ExifInterface.ORIENTATION_ROTATE_90: {
                photoRotation = 90.0f;
                break;
            }
            case ExifInterface.ORIENTATION_ROTATE_180: {
                photoRotation = 180.0f;
                break;
            }
            case ExifInterface.ORIENTATION_ROTATE_270: {
                photoRotation = 270.0f;
                break;
            }
        }
    } catch (IOException e) {
            Log.d("ODDREAMS", e.getMessage());
    }

    if (!hasRotation) {
        try {
                String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION};
                Cursor cursor = getActivity().getContentResolver().query(photoURI, columns, null, null, null);

                if (cursor == null) return 0;

                if (cursor.moveToFirst()) {
                    int orientationColumnIndex = cursor.getColumnIndex(columns[1]);
                    photoRotation = cursor.getInt(orientationColumnIndex);
                    Log.d("ODDREAMS", "CURSOR " + photoRotation);
                }
                cursor.close();
        }
        catch (Exception e) {}

    }

    return photoRotation;
}