Search code examples
androidkotlincameraandroid-camerax

How do we detect the Orientation of Image captured using CameraX if Application's default orientation is set to Portrait Mode


Basically, My camera app is set to Portrait Mode. However, user can take photos in Potrait or landscape by rotating the phone accordingly (The app doesnt rotate).

So my question is, how can we find the captured image orientation?

I tried using DisplayManager.DisplayListener, however, it works only when orientation of app happens. Since I have blocked the orientation of app to portrait mode, it doesnt get any callbacks here.

I even tried using ExifInterface, however, it always gives 6 as rotation.

I am looking for solution using CameraX apis.


Solution

  • I had this problem also. What solved it is by using the device sensor data to get the correct orientation, then set it in my imageCapture object. See snippet below.

            orientationEventListener = object : OrientationEventListener(context) {
                override fun onOrientationChanged(orientation: Int) {
                    // Monitors orientation values to determine the target rotation value
                    val rotation = if (orientation >= 45 && orientation < 135) {
                        Surface.ROTATION_270
                    } else if (orientation >= 135 && orientation < 225) {
                        Surface.ROTATION_180
                    } else if (orientation >= 225 && orientation < 315) {
                        Surface.ROTATION_90
                    } else {
                        Surface.ROTATION_0
                    }
    
                    imageCapture?.setTargetRotation(rotation)
                }
            }
    

    This is also the recommended approach from a similar issue in the Google Issue Tracker: https://issuetracker.google.com/issues/144944155