Skip to main content

How to open the ImagePicker in Kotlin Android

How to open the ImagePicker in Kotlin Android.

Here is a step-by-step tutorial on how to open the ImagePicker in Kotlin for Android:

  1. First, make sure you have the necessary dependencies in your app's build.gradle file. Add the following line to the dependencies block:
implementation 'com.github.dhaval2404:imagepicker:1.7'
  1. Next, open the activity or fragment where you want to use the ImagePicker. In the onCreate method, initialize the ImagePicker library by adding the following code:
.setFolderTitle("Select Image")

Let's go through each line of code:

  • ImagePicker.with(this): Initialize the ImagePicker library with the current activity or fragment as the context.
  • .setFolderMode(true): Enable the folder mode, which allows the user to select images from specific folders.
  • .setFolderTitle("Select Image"): Set the title of the folder selection dialog.
  • .setRootDirectoryName(ImagePickerUtils.ROOT_DIR_DCIM): Set the root directory name for the folder selection dialog.
  • .setDirectoryName(ImagePickerUtils.DIR_NAME): Set the name of the directory where the selected images will be saved.
  • .setMultipleMode(false): Disable multiple image selection.
  • .setShowCamera(true): Show the camera option in the picker.
  • .setRequestCode(100): Set the request code for the image picker. You can use any value here.
  • .start(): Start the image picker.
  1. Next, override the onActivityResult method in your activity or fragment to handle the result of the image picker. Add the following code:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (requestCode == 100 && resultCode == Activity.RESULT_OK && data != null) {
val images: ArrayList<Image> = ImagePicker.getImages(data)

// Handle the selected images here
for (image in images) {
val imagePath = image.path
// Do something with the image path

In this code, we check if the request code matches the one we set in the image picker initialization. If it does, and the result is successful, we can retrieve the selected images using ImagePicker.getImages(data). The selected images are returned as a list of Image objects, where each object contains information about the image, such as its path.

  1. Finally, don't forget to add the necessary permissions to your AndroidManifest.xml file. Add the following lines:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

These permissions are required to access the user's device storage and save the selected images.

That's it! You have now successfully implemented the ImagePicker in your Kotlin Android app. You can customize the behavior and appearance of the ImagePicker using various methods available in the library.