拍照时如何获取设备方向

How can I get the device orientation when a photo was taken

我从来没有像今天这样为图像苦苦挣扎,非常感谢您的帮助 :D
所以,问题是,我正在使用内置相机拍摄照片,然后将其发送到后端进行保存,但是 Kit kat 尤其是 Samsung 设备的方向混乱了。我尝试使用每个人建议的 exif 界面,但我无法获取照片方向。
几分钟前,我找到了一个与此有关的答案,说也许一个好的解决方案是在拍摄照片时保存设备方向,这听起来不错,但是,我不知道如何使用内置的在相机中,因为用 Intent 打开相机时我没有完全控制,像这样:

mPathToTakenImage = ImageProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider",
            newFile);

    openCamera.putExtra(MediaStore.EXTRA_OUTPUT, mPathToTakenImage);
    openCamera.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    startActivityForResult(openCamera, AlgebraNationConstants.TAKE_PHOTO_REQUEST_CODE);

那么,如何在拍摄图像时获取设备方向以便正确旋转图像?
这是旋转图像的代码,但是,我总是得到零:

        final Bitmap finalImg;
        final StringBuilder base64Image = new StringBuilder("data:image/jpeg;base64,");

        final ExifInterface exifInterface;

        try {
            final String imagePath = params[0].getPath();

            exifInterface = new ExifInterface(imagePath);

            final int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_UNDEFINED);

            final Bitmap takenPhoto = MediaStore.Images.Media.getBitmap(mRelatedContext.getContentResolver(),
                    params[0]);

            if (null == takenPhoto) {
                base64Image.setLength(0);
            } else {
                finalImg = rotateBitmap(takenPhoto, orientation);

                if (null == finalImg) {
                    base64Image.setLength(0);
                } else {
                    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    finalImg.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayOutputStream);
                    final byte[] byteArray = byteArrayOutputStream.toByteArray();
                    base64Image.append(Base64.encodeToString(byteArray, Base64.DEFAULT));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return base64Image.length() == 0 ? null : base64Image.toString();

我对此感到疯狂,我们将不胜感激任何帮助。

编辑:

A Uri 不是文件。除非Uri的方案是file,否则getPath()是没有意义的。在您的情况下,该方案主要是 content,而不是 file。目前,您没有获得 EXIF headers,因为 ExifInterface 找不到该文件。

使用 ContentResolveropenInputStream()Uri 标识的内容上打开 InputStream。将 InputStream 传递给 the android.support.media.ExifInterface constructor

此外,请记住,您在使用 OutOfMemoryError 时大部分时间都会崩溃,因为您没有堆 space 来保存 base64 编码的照片。

所以,我终于用这两个答案解决了我的问题:

一般来说,问题是由于磁盘中的图像分配问题,因为我不知道为什么 Android 不喜欢我给出自己的路径来保存拍摄的图像。最后,Intent打开相机是这样的:
final Intent openCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(openCamera, AlgebraNationConstants.TAKE_PHOTO_REQUEST_CODE);

Android 本身正在解决放置图像的位置。尽管如此,@CommonsWare 感谢您的启发和回答。