Skip to main content

How to implement ImagePicker in Kotlin Android

How to implement ImagePicker in Kotlin Android.

Here's a step-by-step tutorial on how to implement ImagePicker in Kotlin for Android:

Step 1: Add dependencies

First, you need to add the necessary dependencies in your app-level build.gradle file. Open the build.gradle file and add the following lines of code:

dependencies {
implementation 'com.github.dhaval2404:imagepicker:1.7'

Step 2: Request necessary permissions

To use the ImagePicker library, you need to request the necessary permissions in your AndroidManifest.xml file. Open the file and add the following lines of code:

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

Step 3: Create a button in your layout file

Next, you need to create a button in your layout file to trigger the image selection. Open your activity's layout file (e.g., activity_main.xml) and add the following code:

android:text="Select Image" />

Step 4: Initialize ImagePicker in your activity

In your activity file (e.g., MainActivity.kt), initialize the ImagePicker library by adding the following code inside the onCreate() method:

import com.github.dhaval2404.imagepicker.ImagePicker

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

val selectImageButton = findViewById<Button>(
selectImageButton.setOnClickListener {

Step 5: Handle the image selection result

To handle the image selection result, override the onActivityResult() method in your activity file and add the following code:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (requestCode == ImagePicker.REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
val fileUri = data?.data
// Use the selected image fileUri
} else if (resultCode == ImagePicker.RESULT_ERROR) {
val error = ImagePicker.getError(data)
// Handle the error

Step 6: Run the app

Finally, run your app on an Android device or emulator. When you click the "Select Image" button, you'll be prompted to choose an image from your device's gallery or camera. Once you select an image, the selected image fileUri will be available in the onActivityResult() method.

That's it! You have successfully implemented ImagePicker in Kotlin for Android.