Taking pictures using Jetpack Compose
2 min readOct 17, 2023
Grab a cup of coffee ☕ and let’s see how can we use Jetpack Compose to take photos directly in the app.
Before starting, let’s add the camera permission to the AndroidManifest.xml
file.
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
Firstly, we need to create a variable to store the bitmap we’ll get after taking the photo.
var bitmap by remember {
mutableStateOf<Bitmap?>(null)
}
Now to open the camera we need to use rememberLauncherForActivityResult
that has a TakePicturePreview
contract.
val cameraLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicturePreview(),
onResult = { newImage ->
bitmap = newImage
}
)
Let's create the permission launcher, which will request camera permission and launch the camera preview if permission is granted.
val permissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
cameraLauncher.launch()
}
}