Getting Started with CameraX

CameraX, launched at Google IO 19 , is a Jetpack support library, built to help us make camera app development easier. It provides a consistent and easy-to-use API surface that works across most Android devices, with backward-compatibility to Android 5.0 (API level 21).

Why CameraX is beneficial?

As per the documentation, CameraX has following primary benefits

  1. Consistence across the devices
  2. It provide new camera experience to the user

Create Android Project with minimum APL level 21.

defaultConfig {
applicationId "com.ankkumar.cameraxsampleapp"
minSdkVersion 21
targetSdkVersion 28
......
}

Add dependencies in app

implementation "androidx.camera:camera-core:1.0.0-alpha01"
implementation "androidx.camera:camera-camera2:1.0.0-alpha01"

Request Camera Permissions

In the manifest file

<uses-permission android:name="android.permission.CAMERA" />
import android.Manifest
import android.util.Size
import android.graphics.Matrix
import java.util.concurrent.TimeUnit
private const val REQUEST_CODE_PERMISSIONS = 881

private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)

Create and Implement view finder

  1. create view finder in activity_main.xml
private lateinit var viewFinder: TextureView
viewFinder = findViewById(R.id.finder_view)

Implementing Image Capture

Write below code to capture image

// Every time the viewfinder is updated, recompute layout
preview.setOnPreviewOutputUpdateListener {

val parent = viewFinder.parent as ViewGroup
parent.removeView(viewFinder)
parent.addView(viewFinder, 0)

viewFinder.surfaceTexture = it.surfaceTexture
updateTransform()
}
CameraX.bindToLifecycle(this, preview)
CameraX.bindToLifecycle(this, preview, imageCapture)

Analysing image capture

create a class called ImageAnalyzer as below

class ImageAnalyzer : ImageAnalysis.Analyzer {
override fun analyze(image: ImageProxy?, rotationDegrees: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}

}
// Setup image analysis pipeline that computes average pixel luminance
val analyzerConfig = ImageAnalysisConfig.Builder().apply {
// Use a worker thread for image analysis to prevent glitches
val analyzerThread = HandlerThread(
"LuminosityAnalysis"
).apply { start() }
setCallbackHandler(Handler(analyzerThread.looper))
// In our analysis, we care more about the latest image than
// analyzing *every* image
setImageReaderMode(
ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE
)
}.build()
Clap, share if you like it and follow for the updates.

Polyglot Fullstack Developer