Mastering Camera Usage in Kotlin for Android Applications

Reza Ramesh
4 min readAug 19, 2023

In recent times, the seamless integration of camera functionality within mobile applications has brought about a revolutionary transformation in enhancing user experiences across diverse domains. From the dynamic landscapes of social networking platforms to the realms of efficient video conferencing solutions, the camera has metamorphosed into an indispensable tool that empowers modern applications. In this digital era, where visual engagement is paramount, the role of the camera cannot be overstated.

At the heart of this camera evolution lies Kotlin, a contemporary and expressive programming language tailored for Android app development. With its elegant syntax and robust feature set, Kotlin provides developers with a conducive environment to unlock the full potential of camera capabilities. In this article, we embark on an illuminating journey, unraveling the intricacies of camera integration within Kotlin-based Android applications. As we delve deeper, you’ll gain insights and mastery over this art through a series of enlightening examples that illuminate the path to harnessing the power of the camera in the Kotlin ecosystem.

Getting Started

Before we embark on our journey into camera integration, it’s recommended to have a basic grasp of Kotlin and Android app development. Familiarity with Android Studio, the primary Integrated Development Environment (IDE) for Android, is also advantageous. Let’s commence our exploration by creating a new project:

  1. Start a New Project: Launch Android Studio and initiate a new Kotlin project.
  2. Permission Setup: In the AndroidManifest.xml file, insert the necessary permissions for camera access and external storage:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Camera Access with CameraX

To access the device’s camera, Android provides two main APIs: the traditional Camera API and the more modern CameraX API. In this article, we will focus on the CameraX API due to its enhanced flexibility and consistent behavior across different devices.

Setting Up CameraX

  1. Add Dependencies: In the build.gradle file of your app module, include the required dependencies:
implementation "androidx.camera.camera2:camera-camera2:1.1.0"
implementation "androidx.camera.lifecycle:lifecycle-camera:1.1.0"

2. Configure CameraX: In your designated activity or fragment, set up CameraX in the onCreate method:

import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

private lateinit var cameraProvider: ProcessCameraProvider
private lateinit var cameraSelector: CameraSelector
private lateinit var preview: Preview

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
preview = Preview.Builder().build()

val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
cameraProvider = cameraProviderFuture.get()

bindPreview()
}, ContextCompat.getMainExecutor(this))
}

private fun bindPreview() {
preview.setSurfaceProvider(previewView.createSurfaceProvider())

val camera = cameraProvider.bindToLifecycle(
this, cameraSelector, preview
)
}
}

In this snippet, we’re incorporating the CameraX library to establish a camera preview, selecting the default back camera and connecting it to a preview view defined in the layout file (activity_main.xml).

Capturing Images with CameraX

Moving beyond the camera preview, let’s explore the process of capturing images using the CameraX library.

Image Capture Configuration

  1. Add Dependencies: To enable image capture, add the relevant dependency:
implementation "androidx.camera.camera2:camera-camera2:1.1.0"
  1. Capture Images: Extend the MainActivity class to encompass image capture functionality:
import androidx.camera.core.ImageCapture
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {

// ... existing code ...

private lateinit var imageCapture: ImageCapture
private lateinit var outputDirectory: File
private lateinit var cameraExecutor: ExecutorService

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// ... existing code ...

imageCapture = ImageCapture.Builder()
.build()

outputDirectory = getOutputDirectory()

cameraExecutor = Executors.newSingleThreadExecutor()
}

private fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() }
}
return mediaDir ?: filesDir
}

private fun takePhoto() {
val imageCapture = imageCapture ?: return

val photoFile = File(
outputDirectory,
SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss",
Locale.US
).format(System.currentTimeMillis()) + ".jpg"
)

val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()

imageCapture.takePicture(
outputOptions, cameraExecutor,
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
// Image saved successfully
}

override fun onError(exception: ImageCaptureException) {
// Handle error
}
})
}

// ... rest of the code ...

}

Here, the ImageCapture object is configured to capture images, and they are saved in the specified output directory. The captured images are timestamped for better organization.

Conclusion

This comprehensive guide has walked you through the intricate process of integrating camera functionality into Android applications using Kotlin and the CameraX library. While we focused on camera previews and image capture, remember that camera integration offers a vast array of possibilities, including real-time filters, video recording, and augmented reality experiences.

As you continue your development journey, keep exploring the potential of the CameraX API. Experiment with diverse camera-related features to craft captivating user experiences. Embrace Kotlin’s power and CameraX’s versatility to elevate your app to new heights. Happy coding!

LinkedInGithub

Useful Links:

--

--

Reza Ramesh

I am an Android developer and UI/UX designer with 4 years of experience in creating engaging and user-friendly mobile applications