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.

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.

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)
}

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.

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

Next: 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.

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: