Skip to main content

How to rotate the selected image using ImagePicker in Kotlin Android

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

Here is a detailed step-by-step tutorial on how to rotate a selected image using ImagePicker in Kotlin for Android:

Step 1: Set up the project

  1. Create a new project in Android Studio.
  2. Add the necessary dependencies in your app-level build.gradle file:
    implementation 'androidx.appcompat:appcompat:1.3.0'
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    implementation 'com.github.bumptech.glide:compiler:4.12.0'
    implementation 'com.github.yalantis:ucrop:2.2.3-native'

Step 2: Add permissions and dependencies

  1. Open the AndroidManifest.xml file and add the following permissions:
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  2. Add the following provider tag inside the application tag:
    <provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/file_paths" />
    </provider>
  3. Create a new XML file called file_paths.xml inside the res/xml folder and add the following code:
    <paths>
    <external-path name="external_files" path="."/>
    </paths>

Step 3: Implement ImagePicker

  1. Create a new Kotlin class called ImagePicker.kt and add the following code:

    import android.app.Activity
    import android.content.Intent
    import android.provider.MediaStore
    import androidx.core.content.FileProvider
    import java.io.File
    import java.io.IOException
    import java.text.SimpleDateFormat
    import java.util.*

    class ImagePicker(private val activity: Activity) {
    private var currentPhotoPath: String? = null

    fun selectImageFromGallery() {
    val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
    activity.startActivityForResult(intent, REQUEST_PICK_IMAGE)
    }

    fun captureImage() {
    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    if (intent.resolveActivity(activity.packageManager) != null) {
    val photoFile: File? = try {
    createImageFile()
    } catch (ex: IOException) {
    null
    }
    photoFile?.also {
    val photoURI = FileProvider.getUriForFile(activity, "${activity.packageName}.provider", it)
    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
    activity.startActivityForResult(intent, REQUEST_CAPTURE_IMAGE)
    }
    }
    }

    private fun createImageFile(): File {
    val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
    val storageDir: File? = activity.getExternalFilesDir(null)
    return File.createTempFile("JPEG_${timeStamp}_", ".jpg", storageDir).apply {
    currentPhotoPath = absolutePath
    }
    }

    fun getCurrentPhotoPath(): String? {
    return currentPhotoPath
    }

    companion object {
    const val REQUEST_PICK_IMAGE = 100
    const val REQUEST_CAPTURE_IMAGE = 200
    }
    }

Step 4: Implement image rotation

  1. Add the following code to your Activity or Fragment where you want to use the ImagePicker:

    import android.app.Activity
    import android.content.Intent
    import android.graphics.Bitmap
    import android.graphics.Matrix
    import android.os.Bundle
    import android.provider.MediaStore
    import android.widget.ImageView
    import androidx.appcompat.app.AppCompatActivity
    import com.bumptech.glide.Glide
    import com.bumptech.glide.request.RequestOptions
    import com.yalantis.ucrop.UCrop
    import java.io.File

    class MainActivity : AppCompatActivity() {
    private lateinit var imagePicker: ImagePicker
    private lateinit var imageView: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    imagePicker = ImagePicker(this)
    imageView = findViewById(R.id.imageView)

    // Set click listener on a button to select image from gallery
    // or capture image using camera
    findViewById<Button>(R.id.buttonSelectImage).setOnClickListener {
    imagePicker.selectImageFromGallery()
    }

    findViewById<Button>(R.id.buttonCaptureImage).setOnClickListener {
    imagePicker.captureImage()
    }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
    when (requestCode) {
    ImagePicker.REQUEST_PICK_IMAGE -> {
    val selectedImageUri = data?.data
    selectedImageUri?.let {
    // Start image cropping
    startCropActivity(selectedImageUri)
    }
    }
    ImagePicker.REQUEST_CAPTURE_IMAGE -> {
    val photoPath = imagePicker.getCurrentPhotoPath()
    photoPath?.let {
    // Start image cropping
    startCropActivity(Uri.fromFile(File(photoPath)))
    }
    }
    UCrop.REQUEST_CROP -> {
    val croppedImageUri = UCrop.getOutput(data!!)
    croppedImageUri?.let {
    // Load the cropped image into ImageView
    Glide.with(this)
    .load(croppedImageUri)
    .apply(RequestOptions.circleCropTransform())
    .into(imageView)
    }
    }
    }
    }
    }

    private fun startCropActivity(sourceUri: Uri) {
    val destinationUri = Uri.fromFile(File(cacheDir, "cropped_image.jpg"))

    UCrop.of(sourceUri, destinationUri)
    .withAspectRatio(1f, 1f)
    .start(this)
    }

    private fun rotateImage(bitmap: Bitmap, degrees: Float): Bitmap {
    val matrix = Matrix()
    matrix.postRotate(degrees)
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }
    }

That's it! You have successfully implemented the image rotation functionality using ImagePicker in Kotlin for Android.