Capture Photo using Jetpack Compose

Mohit Suthar
2 min readAug 2, 2022

--

Hello Folks,

The best thing in Compose is to reduce much boilerplate code which we write in our old pattern.

It's very easy to capture a photo, isn't it? so lets capture

I hope you are aware of the JC :) So basically you need to consider three steps

The first is Add Permissions and second asking the permission and the last one is to get result from the Activity, it's very simple to start with it let's do it

  1. Add Basic Permissions in Manifest Files
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />

2. Now you need to check that permission is allowed or not in the code

val multiplePermissionsState = rememberMultiplePermissionsState(
listOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
)
)
multiplePermissionsState.launchMultiplePermissionRequest()

launchMultiplePermissionRequest() for asking permission to user for allowing or denied.

3. Now we need to open Camera to capture image so you need to open launcherActivityResult, check the below code for more understanding

val launcherCamera =
rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap ->
//Here you will get the Bitmap of the image
}

suppose in the Jetpack Compose we have Image and having on the press of that image than how we will get the bitmap than you can check from below code

Image(
painter = painterResource(id = R.drawable.ic_camera),
contentDescription = "Camera",
modifier = Modifier.clickable {
if (multiplePermissionsState.allPermissionsGranted) {
launcherCamera.launch()
}else{
multiplePermissionsState.launchMultiplePermissionRequest()
}
})

In the above code first, check the permission if it's all allowed then launch the camera launcher Activity to get the bitmap. launcherCamera.launch() method to launch the Camera intent.

Now you can process your bitmap and save in the file and use it. :)

I have added some code for your help so you can check and implement it in your way.

Note: I will upload the demo link later and Thanks for reading and sharing your feedback in a comment.

Capture Image From Camera

--

--