Uri to bitmap conversion rotates the image

273 Views Asked by At

I have an app that has image upload feature and after uploading the image on onActivityResult() I receive the Uri of the image and turn it into bitmap with the following function :

    private fun uriToBitmap(selectedFileUri: Uri): Bitmap? {
        return try {
            val parcelFileDescriptor: ParcelFileDescriptor =
                requireContext().contentResolver.openFileDescriptor(selectedFileUri, "r")!!
            val fileDescriptor: FileDescriptor = parcelFileDescriptor.fileDescriptor
            val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
            parcelFileDescriptor.close()
            image
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }

but for some reason my image rotates 90 degrees if it was a portrait image

I have tried using the ExifInterface thing for fixing it and rotating it back with this function :

fun determineImageRotation(imageFile: File, bitmap: Bitmap): Bitmap {
    val exif = ExifInterface(imageFile.absolutePath)
    val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0)
    val matrix = Matrix()
    when (orientation) {
        6 -> matrix.postRotate(90f)
        3 -> matrix.postRotate(180f)
        8 -> matrix.postRotate(270f)
    }
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}

but I receive this error :

ExifInterface got an unsupported image format file(ExifInterface supports JPEG and some RAW image formats only) or a corrupted JPEG file to ExifInterface.
    java.io.EOFException

this is how I create a file path for the image :

    @Throws(IOException::class)
    private fun createImageFile(): File {
        // Create an image file name
        val timeStamp: String =
            SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
            "PNG_${timeStamp}_", /* prefix */
            ".png", /* suffix */
            storageDir /* directory */
        )
    }

here is an example of a file path that I have for an image :

/storage/emulated/0/Android/data/avedot.app/files/Pictures/PNG_20210622_094219_232594250744276112.png

I assume there is something with the path that is related to the dot in avedot.app whice breaks the ExifInterface function but how can I work around this ?

Thanks in advance !

0

There are 0 best solutions below