Created
August 28, 2021 17:00
-
-
Save eldetulado/44a21030ba5059833c5326a25cd0debd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun getPathFromURI(context: Context, uri: Uri): String { | |
var realPath = "" | |
uri.path?.let { path -> | |
val databaseUri: Uri | |
val selection: String? | |
val selectionArgs: Array<String>? | |
if (path.contains("/document/image:")) { // files selected from "Documents" | |
databaseUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI | |
selection = "_id=?" | |
selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1]) | |
} else { // files selected from all other sources, especially on Samsung devices | |
databaseUri = uri | |
selection = null | |
selectionArgs = null | |
} | |
try { | |
val column = "_data" | |
val projection = arrayOf(column) | |
val cursor = context.contentResolver.query( | |
databaseUri, | |
projection, | |
selection, | |
selectionArgs, | |
null | |
) | |
cursor?.let { | |
if (it.moveToFirst()) { | |
val columnIndex = cursor.getColumnIndexOrThrow(column) | |
realPath = cursor.getString(columnIndex) | |
} | |
cursor.close() | |
} | |
} catch (e: Exception) { | |
Log.e("TAG", "getPathFromURI: EXCEPTION $e") | |
} | |
} | |
return realPath | |
} | |
// Example how to use | |
val file = File(getPathFromURI(this, it)) | |
if (file.exists()) { | |
val bitMap = BitmapFactory.decodeFile(file.absolutePath) | |
binding.ivPhotoPet.setImageBitmap(bitMap) | |
} else { | |
Toast.makeText(this, "No se pudo cargar la imagen", Toast.LENGTH_SHORT).show() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment