Pick Image From Gallery in Kotlin – Android

This article contains a step by step guide to pick an image from the Gallery in Kotlin Android.

Pick Image From Gallery in Kotlin
Pick Image From Gallery in Kotlin

Before starting, add the following READ_EXTERNAL_STORAGE permission in your Manifest.xml file above the application tag.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

You also need to add Runtime permissions for API Level 19 & above. This article will help you to Ask Runtime Permissions in Kotlin Android.

Method to Pick Image From Gallery in Kotlin

After adding permissions you can call the following method to pick an image from Gallery.

private fun openGalleryForImage() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        startActivityForResult(intent, REQUEST_CODE)
    }

The above method will open the phone’s default Gallery App. After choosing an image, Gallery will automatically be closed and your Activity’s onActivityResult method will be called. The code is the following.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE){
            imageView.setImageURI(data?.data) // handle chosen image
        }
    }

in the Above ‘onActivityResult‘ method, you receive an Intent object which contains all data about the selected image.

REQUEST_CODE is a constant integer value, which can be initialized with any number at the class level, like below.

val REQUEST_CODE = 100

That’s it 🙂

Optional

If you want to get Bitmap From ImageView in Kotlin, you can use the following code.

var bitmap = (imageView.drawable as BitmapDrawable).bitmap

For further operations on Bitmap & Images, like resizing, have a look at our post Resize Bitmap by Keeping the Same Aspect Ratio in Kotlin.

If you have any questions, don’t hesitate to ask in the comments section below.

Next:

Capture Photo with Camera in Kotlin – Android

Pick Multiple Images From Gallery in Kotlin

You can also visit our Coding Articles & Tutorials Knowledge Base for other helping code snippets.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

One thought on “Pick Image From Gallery in Kotlin – Android

  1. Spot on with this write-up, I actually suppose this website needs much more consideration. I’ll most likely be once more to read rather more, thanks for that info.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: