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?) {
        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.

Don’t forget to visit our Coding Articles & Tutorials Knowledge Base for other helping code snippets.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

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