Skip to content

Instantly share code, notes, and snippets.

@Andrew0000
Created April 20, 2023 08:17
Show Gist options
  • Select an option

  • Save Andrew0000/2e314219e6752f632a40a720e9914332 to your computer and use it in GitHub Desktop.

Select an option

Save Andrew0000/2e314219e6752f632a40a720e9914332 to your computer and use it in GitHub Desktop.
Android: Pick photo from gallery + read by uri without extra permissions
fun launch() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
startActivityForResult(intent, 2)
}
//TODO use registerForActivityResult() as modern approach
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode === 2 && resultCode === Activity.RESULT_OK) {
if (data != null) {
val imageUri: Uri? = data.getData()
imageUri?.let {
val stream = requireContext().getContentResolver().openInputStream(it)
val b = BitmapFactory.decodeStream(stream, null, null)
Timber.i("test_ bitmap: ${b?.width} / ${b?.height}")
binding.imageView.setImageBitmap(b)
//binding.imageView.setImageURI(it)
}
}
}
}
@Andrew0000
Copy link
Author

@Andrew0000
Copy link
Author

Get extension:

val mime = contentResolver.getType(uri)
val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment