Created
April 20, 2023 08:17
-
-
Save Andrew0000/2e314219e6752f632a40a720e9914332 to your computer and use it in GitHub Desktop.
Android: Pick photo from gallery + read by uri without extra permissions
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
| 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) | |
| } | |
| } | |
| } | |
| } |
Author
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
https://developer.android.com/training/data-storage/shared/documents-files#bitmap