Android CameraX: Difference between revisions
Line 174: | Line 174: | ||
Glad I watched this course, the compose stuff looks like it will improve people speed a lot. Next take the photo and you can see this is now trivial. We just make a function and call it | Glad I watched this course, the compose stuff looks like it will improve people speed a lot. Next take the photo and you can see this is now trivial. We just make a function and call it | ||
<syntaxhighlight lang="kotlin"> | <syntaxhighlight lang="kotlin"> | ||
IconButton( | |||
onClick = { | |||
takePhoto( | |||
controller = controller, | |||
onPhotoTaken = viewModel::onTakePhoto | |||
) | |||
} | |||
) { | |||
Icon( | |||
imageVector = Icons.Default.PhotoCamera, | |||
contentDescription = "Take Photo" | |||
) | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
And here is the function called | |||
<syntaxhighlight lang="kotlin"> | <syntaxhighlight lang="kotlin"> | ||
private fun takePhoto( | private fun takePhoto( | ||
Line 181: | Line 195: | ||
) { | ) { | ||
controller.takePicture( | controller.takePicture( | ||
ContextCompat.getMainExecutor(applicationContext) | ContextCompat.getMainExecutor(applicationContext), | ||
object: OnImageCapturedCallback() { | object: OnImageCapturedCallback() { | ||
override fun onCaptureSuccess(image: ImageProxy) { | override fun onCaptureSuccess(image: ImageProxy) { | ||
onPhotoTaken(image.toBitmap()) | onPhotoTaken(image.toBitmap()) | ||
Log.i("CameraXTut", "Taken a picture") | |||
} | } | ||
Revision as of 06:16, 6 March 2025
Introduction
Already had this working for my Food app but this is now broken so watching a tutorial and thought I better take notes
Setup Permissions
Make sure we give permissions in the Manifest
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Implement Permission Checking
This is the simplest way to get going
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!hasRequiredPermissions()) {
requestPermissions(CAMERAX_PERMISSIONS, 0)
}
enableEdgeToEdge()
}
private fun hasRequiredPermissions(): Boolean {
return CAMERAX_PERMISSIONS.all {
ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
}
}
companion object {
private val CAMERAX_PERMISSIONS = arrayOf(
android.Manifest.permission.CAMERA,
android.Manifest.permission.RECORD_AUDIO
)
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
}
Compose
I am loving the new compose. It takes a lot of the tedium out of it all. This did not exist last time. Basically bye, bye XML. Lot of code here but you just make the bits and add the components inline. The CameraPreview is the implementation of the previewer in Xml. This
setContent {
CameraXTutTheme {
Scaffold {
val scaffoldState = rememberBottomSheetScaffoldState()
val controller = remember {
LifecycleCameraController(applicationContext).apply {
setEnabledUseCases(
CameraController.IMAGE_CAPTURE or
CameraController.VIDEO_CAPTURE
)
}
}
BottomSheetScaffold(
scaffoldState = scaffoldState,
sheetPeekHeight = 0.dp,
sheetContent = {
}
) { padding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(padding)
) {
CameraPreview(
controller,
Modifier.fillMaxSize()
)
IconButton(
onClick = {
controller.cameraSelector =
if (controller.cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA) {
CameraSelector.DEFAULT_FRONT_CAMERA
} else {
CameraSelector.DEFAULT_BACK_CAMERA
}
},
modifier = Modifier.padding(16.dp)
) {
Icon(
imageVector = Icons.Default.Cameraswitch,
contentDescription = "Switch Camera"
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter)
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceAround
) {
IconButton(
onClick = {
}
) {
Icon(
imageVector = Icons.Default.Photo,
contentDescription = "Open Gallery"
)
}
IconButton(
onClick = {
}
) {
Icon(
imageVector = Icons.Default.PhotoCamera,
contentDescription = "Take Photo"
)
}
}
}
}
}
}
}
Add A Panel (Sheet) to Display Taken Images
First we create a sheet to display the images take on, this really is an excuse to document something to remind me what to do
@Composable
fun PhotoBottomSheetContent(
bitmaps: List<Bitmap>,
modifier: Modifier
) {
if(bitmaps.isEmpty()) {
Box(
modifier = modifier
.padding(16.dp),
contentAlignment = Alignment.Center
)
{
Text ("No photos taken yet")
}
} else {
LazyVerticalStaggeredGrid(
columns = StaggeredGridCells.Fixed(2),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalItemSpacing = 16.dp,
contentPadding = PaddingValues(16.dp),
modifier = modifier
) {
items(bitmaps) { bitmap ->
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = null,
modifier = Modifier
.clip(RoundedCornerShape(10.dp))
)
}
}
}
}
This is the code for the Panel is this photo
Taking A Photo
Glad I watched this course, the compose stuff looks like it will improve people speed a lot. Next take the photo and you can see this is now trivial. We just make a function and call it
IconButton(
onClick = {
takePhoto(
controller = controller,
onPhotoTaken = viewModel::onTakePhoto
)
}
) {
Icon(
imageVector = Icons.Default.PhotoCamera,
contentDescription = "Take Photo"
)
}
And here is the function called
private fun takePhoto(
controller: LifecycleCameraController,
onPhotoTaken: (Bitmap) -> Unit
) {
controller.takePicture(
ContextCompat.getMainExecutor(applicationContext),
object: OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
onPhotoTaken(image.toBitmap())
Log.i("CameraXTut", "Taken a picture")
}
override fun onError(exception: ImageCaptureException) {
super.onError(exception)
Log.e("CameraXTut", "Error capturing image", exception)
}
}
)
}