Image path for EXIFInterface

Viewed 20

I use this code to get an image's path and then try to get it's EXIF data to check rotation but the code crashes with the message "Caused by: java.io.FileNotFoundException: /external/images/media/12729 (No such file or directory)" at line

val ei = selectedImage.path?.let { ExifInterface(it) }

My code is

fun getImagepath(activity: Activity): Uri? {
    val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val imageId: Long
    val columnIndexID: Int
    val projection = arrayOf(MediaStore.Images.Media._ID)
    cursor = activity.contentResolver.query(uriExternal, projection, null, null, null)
    return if (cursor != null) {
        columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        cursor.moveToLast()
        imageId = cursor.getLong(columnIndexID)
        val uriImage = Uri.withAppendedPath(uriExternal, "" + imageId)
        cursor.close()
        uriImage
    } else {
        null
    }
}

private fun rotateImageIfRequired(img: Bitmap, selectedImage: Uri): Bitmap {
    val ei = selectedImage.path?.let { ExifInterface(it) }
    when (ei?.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)) {
        ExifInterface.ORIENTATION_ROTATE_90 -> {
            return rotateImage(img, 90)
        }
        ExifInterface.ORIENTATION_ROTATE_180 -> {
            return rotateImage(img, 180)
        }
        ExifInterface.ORIENTATION_ROTATE_270 -> {
            return rotateImage(img,270)
        }
    }
    return img
}
1 Answers

Make sure that you are using the Jetpack edition of ExifInterface. Then, replace:

val ei = selectedImage.path?.let { ExifInterface(it) }

with:

val ei = ExifInterface(activity.contentResolver.openInputStream(selectedImage))

And please stop trying to get a path from a Uri.

Related