Skip to main content

How to crop the selected image using ImagePicker in Kotlin Android

How to crop the selected image using ImagePicker in Kotlin Android.

Here's a detailed step-by-step tutorial on how to crop a selected image using ImagePicker in Kotlin for Android:

Step 1: Set up the project

  • Create a new Android project in Android Studio.
  • Open the build.gradle file (Module: app) and add the following dependency:
implementation 'com.github.yalantis:ucrop:2.2.3'

Step 2: Add runtime permissions

  • Declare the necessary permissions in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  • Request the necessary runtime permissions in your activity class.

Step 3: Add ImagePicker library

  • Add the ImagePicker library to your project by following these steps:
    • Open the build.gradle file (Module: app) and add the following dependency:
implementation 'com.github.dhaval2404:imagepicker:1.7'
  • Sync the project to download the library.

Step 4: Add a button to select an image

  • Add a Button element to your activity layout XML file:
<Button
android:id="@+id/btnSelectImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Image"
/>

Step 5: Implement ImagePicker

  • In your activity class, declare a variable to hold the selected image URI:
private var selectedImageUri: Uri? = null
  • Initialize the ImagePicker library in the onCreate() method of your activity:
ImagePicker.with(this)
.compress(1024)
.maxResultSize(1080, 1080)
.start()
  • Implement the onActivityResult() method to handle the image selection:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (requestCode == ImagePicker.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
selectedImageUri = data?.data
// Perform the image cropping
startCrop(selectedImageUri)
}
}
  • Implement the startCrop() method to open the image cropping activity:
private fun startCrop(uri: Uri?) {
val destinationUri = Uri.fromFile(File(cacheDir, "cropImage"))
UCrop.of(uri!!, destinationUri)
.withAspectRatio(1f, 1f)
.start(this)
}

Step 6: Handle the cropped image

  • Implement the onActivityResult() method again to handle the cropped image:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)

if (requestCode == UCrop.REQUEST_CROP && resultCode == Activity.RESULT_OK) {
val croppedImageUri = UCrop.getOutput(data!!)
// Use the cropped image URI as needed
}
}

That's it! You now have a step-by-step guide on how to crop a selected image using ImagePicker in Kotlin for Android. You can customize the cropping aspect ratio, compression, and maximum result size as per your requirements.