Capture Photo with Camera in Kotlin – Android

This article shows a step by step guide to capture a photo with camera in Android using Kotlin. For this purpose, we need to initialize an Intent with MediaStore.ACTION_IMAGE_CAPTURE Action. Then open native Camera App using startActivityForResult(...), as shown in the following code.

1. Add Camera Permission

Before starting, add the following CAMERA permission in your Manifest.xml file above the application tag.

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

For API Level 19 & above, You also need to add Runtime permissions. to avoid crash on runtime, this article will help you to Ask Runtime Permissions in Kotlin Android.

2. Method to Open Camera to Take Image in Kotlin

Call the following method to open the default Camera App of the phone to take a picture.

val REQUEST_CODE = 200

fun capturePhoto() {

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE)
}

3. Receive Captured Photo in onActivityResult Method

As you can see in the above method, it opens Camera Activity for result, so it means we also need to overide onActivityResult(...) method to receive the captured image in Intent. The code is the following.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE && data != null){
        imageView.setImageBitmap(data.extras.get("data") as Bitmap)
    }
}

As you can see, here we receive an Intent object which contains all data about the selected image in the form of Extras.

4. Get Image Path From URI

We have different methods to get full file path from URI depending upon the Android version and the location where the file is picked. I have written a detailed article on the topic. You can Just copy the URIPathHelper class from that article and use it in your code to get the full photo path.
Get Path From URI In Kotlin Android

That’s it. This is how to capture photo with camera in Kotlin.
Enjoy 🙂

Next:

1. Upload Image to Server in Android Kotlin

2. Pick Image From Gallery in Kotlin – Android

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

2 thoughts on “Capture Photo with Camera in Kotlin – Android

    1. No need to check API level but you can check does the Android device support the Camera, Because there are many Android devices which don’t have the hardware camera. You can check that in this way

      if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
      capturePhoto()
      }

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

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

%d bloggers like this: