BitmapFactory.decodeByteArray() works incorrect after using ExifInterface

288 Views Asked by At

I try to add simple functionality with getting picture from gallery or from camera in my Android app. And all works fine, I successfully obtain uri of picture and after that want to show this picture to user. And this code works well:

private fun showImageToUser(uri: Uri) {
    val inputStream = contentResolver?.openInputStream(uri)
    val bytes = inputStream?.readBytes() ?: return
    val bitmapOriginal = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    // show bitmap in ImageView...
}

Then, I want to rotate image if need (for example, after camera all images have 90-degrees rotation). For this I use ExifInterface (from androidx.exifinterface:exifinterface:1.3.1). But there is something strange. In this code:

private fun showImageToUser(uri: Uri) {
        val inputStream = contentResolver?.openInputStream(uri)

        val exifInterface = ExifInterface(inputStream ?: return)
        val rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)

        val bytes = inputStream.readBytes()

        val bitmapOriginal = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
        val bitmapRotated = bitmapOriginal.rotateImageIfRequired(rotation) // simple logic for rotating in rotateImageIfRequired method...
    }

the bitmapOriginal is always null. As you can see, I create exifInterface object before inputStream.readBytes(). If I swap them, and try to run the following code:

private fun showImageToUser(uri: Uri) {
    val inputStream = contentResolver?.openInputStream(uri)
    val bytes = inputStream?.readBytes() ?: return

    val exifInterface = ExifInterface(inputStream)
    val rotation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)

    val bitmapOriginal = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    val bitmapRotated = bitmapOriginal.rotateImageIfRequired(rotation)
} 

then bitmapOriginal will not be null, but the rotation value will be always ORIENTATION_UNDEFINED.

So, what am I doing wrong? How to get correctly bytes and image orientation from uri and create after that bitmap with correct orientation?

0

There are 0 best solutions below