Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android 11 get image orientation from EXIF

Hi I have an app with compileSdkVersion 30 and targetSdkVersion 30. Since I need to know the orientation of image, I wrote these:

val exif = ExifInterface(imageFile.absolutePath)
            val orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )

            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_270 -> rotate = 270
                ExifInterface.ORIENTATION_ROTATE_180 -> rotate = 180
                ExifInterface.ORIENTATION_ROTATE_90 -> rotate = 90
            }

But there was an exception shows like:

java.io,FileNotFoundException:/storage/emulated/0/DCIM/Camera/xxx.jpg: open failed EACCESS(Permission denied)
...
at android.media.ExifInterface.<init>(ExifInterface.java.1389)

What I would like to do is get image and know its orientation, but I can not find any sample on Internet. Can anybody give me a hint? thanks!

like image 593
magic_mickey Avatar asked Nov 16 '22 04:11

magic_mickey


1 Answers

Foi projects with target API 30 you must use support ExifInterface:

implementation "androidx.exifinterface:exifinterface:1.3.2"

and ExifInterface constructor with InputStream:

import androidx.exifinterface.media.ExifInterface

private fun calculateBitmapRotateDegrees(uri: Uri): Float {
    var exif: ExifInterface? = null
    try {
        val inputStream: InputStream? = contentResolver.openInputStream(uri)
        inputStream?.run {
            exif = ExifInterface(this)
        }
    } catch (e: IOException) {
        e.printStackTrace()
    }

    exif?.run {
        val orientation = getAttributeInt(
            ExifInterface.TAG_ORIENTATION,
            ExifInterface.ORIENTATION_NORMAL
        )

        return when (orientation) {
            ExifInterface.ORIENTATION_ROTATE_90 -> 90F
            ExifInterface.ORIENTATION_ROTATE_180 -> 180F
            ExifInterface.ORIENTATION_ROTATE_270 -> 270F
            else -> 0F
        }
    }
    return 0F
}
like image 86
Oleksandr Bodashko Avatar answered Dec 28 '22 23:12

Oleksandr Bodashko