Create Your Own CameraApp Using CameraX

saiteja janjirala
4 min readMar 27, 2021

CameraX is library which provides us to easily access our device camera to capture photos,videos with ease.this library supports for 94% of the devices currently and has a backward compatibility to Android 5.0(Lollipop Api 21).

Lets get Started

Add these dependencies in your app level build.gradle file.

def camerax_version = "1.0.0-beta07"
// CameraX core library using camera2 implementation
implementation "androidx.camera:camera-camera2:$camerax_version"
// CameraX Lifecycle Library
implementation "androidx.camera:camera-lifecycle:$camerax_version"
// CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha14"

Add these in your android block in your app level build.gradle file right after buildtypes

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

and add these in your Manifest.xml file

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>

now we all setup with our dependencies and permissions lets setup our activity.

Creating PreviewScreen

Here we will use the preview view that we get for cameraX that is

<androidx.camera.view.PreviewView
android:id="@+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

This is the view where we are going to show our camera’s preview.

And create a button to capture picture using cameraX.

<Button
android:id="@+id/capture_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="capture" app:layout_constraintBottom_toBottomOf="parent"/>

in Our MainActivity lets setup permission check.

private fun permissionCheck() {
if (Build.VERSION.SDK_INT >= 23) {
val strings = arrayOf(
Manifest.permission.CAMERA,
)
if (ContextCompat.checkSelfPermission(this,
strings[0]) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, strings,CODE)
} else {
setCam()
}
} else {
setCam()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == CODE) {
permissionCheck()
}
}

i am rechecking permissions until i get the permission granted other wise our app won’t work with access to the camera.

Setting up our camera with our preview

There are few things we need to setup our camera with our preview view.

  1. Camera : This Interface has functionalities like zooming,focusing and metering and controls the camera and the data flow from camera to usecase.
  2. ImageCapture: This class provides the functions to take a picture and provides necessary functions to save the result and handle the errors.
  3. VideoCapture: This class provides the functions to take a video and provides necessary functions to save the results and handle the errors.
  4. Preview: It is a usecase provides a camera preview stream to display on the screen.
  5. ProcessCameraProvider : This class is used to bind the lifecycle of the cameras to our application components.
  6. CameraSelector: This class is used to select the front and back cameras of our app while capturing video or photo.

Now Lets Setup Our Camera

var camera: androidx.camera.core.Camera? = null
var imageCapture: ImageCapture? = null
var preview: Preview? = null
private var lensFacing = CameraSelector.LENS_FACING_FRONT
private fun setCam() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener(
Runnable {
val cameraProvider = cameraProviderFuture.get()
preview = Preview.Builder().build()
preview?.setSurfaceProvider(camera_view.surfaceProvider)
imageCapture = ImageCapture.Builder().build()
val cameraSelector =
CameraSelector.Builder().requireLensFacing(lensFacing)
.build()
cameraProvider.unbindAll()
camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)
},
ContextCompat.getMainExecutor(this)
)
}

Here inorder to get cameraProvider from ProcessCameraProvider we have a listener which takes to arguments a Runnable to listen to the listener to get the result of cameraProvider and a Executor to execute our listener.

Here i have used a executor which executes that listener in the mainThread.

then we build our preview object and set it up with our surface provider view where we are going to show our preview.

then we got our cameraSelector object to set which camera to use front or back.

we got our imagecapture object too finally we unbind all the components to which our cameraProvider is bound to and then we bind our camera with our activity with the above components.

Now we are good to go to capture our picture.

Capturing Picture

There are two ways of capturing the picture

1.Handle your output after the capture is success.

imageCapture?.takePicture(ContextCompat.getMainExecutor(this),
object : ImageCapture.OnImageCapturedCallback() {
override fun onCaptureSuccess(image: ImageProxy) {
super.onCaptureSuccess(image)
//Handle your output here
}

override fun onError(exception: ImageCaptureException) {
super.onError(exception)
//handle your error here
}
})

here it takes two parameters first is the executor to execute the image capturing process and second is the callback for the completion of the image capturing.

2. Capture and save your output and handle the saved output

val file = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val tempFile =
File.createTempFile("${System.currentTimeMillis()}", ".jpeg", file)
val outputOptions = ImageCapture.OutputFileOptions.Builder(tempFile).build()
imageCapture?.takePicture(outputOptions,
ContextCompat.getMainExecutor(this),
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
//handle the saved image
}

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

}
)

Here it takes three parameters the fileoptions to save the output to that file,executor to capture and a callback to handle success and failure for capturing and saving results.for using 2nd method add permissions for storage access.

I hope this helps you to understand the basics of how to use cameraX library.

Checkout this for basic understanding of cameraX.

--

--