Android 从 MediaStore Uri 获取方向

Android getting orientation from MediaStore Uri

我似乎无法从 MediaStore Uri 获取图像的正确方向。 Uri 是从设备图库中选择图像后从 Chooser 意图返回的。

我已经尝试了以下我在网上找到的代码的所有组合,但似乎没有任何效果。无论图像的实际方向如何,此代码都将 orientation 设置为 0。

通过查看我设备上的图像细节,我知道实际方向不是 0。

public static void copyAndResizePhoto(Context context, Uri srcUri, File destFile) {
    String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};
    Cursor cursor = context.getContentResolver().query(srcUri, orientationColumn, null, null, null);
    int orientation = -1;
    if (cursor != null && cursor.moveToFirst()) {
        orientation = cursor.getInt(cursor.getColumnIndex(orientationColumn[0]));
    }
    if (cursor != null)
        cursor.close();
}

感谢任何帮助。谢谢。

我的原始解决方案仅适用于从 MediaStore 中选取的图像。以下解决方案适用于任何 Uri,这意味着无论用户从何处选择照片,此方法都会固定其方向。

以下方法需要两个库:metadata-extractor-2.6.4 and xmpcore-5.1.2.jar.

/**
 * Rotates the specified bitmap to the correct orientation. Note that this library requires
 * the following two libraries:
 * 1. <a href="https://code.google.com/p/metadata-extractor/downloads/list">metadata-extractor-2.6.4</a>
 * 2. <a href="https://github.com/drewfarris/metadata-extractor/tree/master/Libraries">xmpcore-5.1.2.jar</a>
 *
 * @param uri The Uri to the photo file.
 * @param bmp The Bitmap representative of the photo file.
 * @return A correctly rotated Bitmap.
 */
private static Bitmap fixOrientation(Uri uri, Bitmap bmp) {
    try {
        InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
        Metadata meta = null;

        if (inputStream != null) {
            try {
                meta = ImageMetadataReader.readMetadata(new BufferedInputStream(inputStream), false);
            } catch (ImageProcessingException e) {
                e.printStackTrace();
            }

            if (meta != null) {
                int orientation = 0;
                ExifIFD0Directory exifIFD0Directory = meta.getDirectory(ExifIFD0Directory.class);

                if (exifIFD0Directory.containsTag(ExifIFD0Directory.TAG_ORIENTATION))
                    try {
                        orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
                    } catch (MetadataException e){
                        e.printStackTrace();
                    }

                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        bmp = rotateBitmap(bmp, 90);
                        break;

                    case ExifInterface.ORIENTATION_ROTATE_180:
                        bmp = rotateBitmap(bmp, 180);
                        break;

                    case ExifInterface.ORIENTATION_ROTATE_270:
                        bmp = rotateBitmap(bmp, 270);
                        break;
                }
            }
        }

    } catch (IOException e) {
        Log.d(TAG, "Error opening InputStream from uri: " + uri.toString());
        e.printStackTrace();
    }

    return bmp;
}

享受, 科恩