Skip to content

Instantly share code, notes, and snippets.

@keima keima/MainActivity.kt
Last active May 5, 2019

Embed
What would you like to do?
Jetpack CameraX sample (ImageCapture)
package app.keima.android.cameraxplayground
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.SurfaceView
import android.view.TextureView
import android.widget.Button
import androidx.camera.core.*
import java.io.File
class MainActivity : AppCompatActivity() {
private val preview: Preview = Preview(
PreviewConfig.Builder().build()
)
private val imageCapture: ImageCapture = ImageCapture(
ImageCaptureConfig.Builder()
.setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY /* or ImageCapture.CaptureMode.MAX_QUALITY */)
.build()
)
private val imageAnalysis = ImageAnalysis(
ImageAnalysisConfig.Builder()
.setImageReaderMode(
ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE
// ImageAnalysis.ImageReaderMode.ACQUIRE_NEXT_IMAGE
)
// .setImageQueueDepth()
.build()
)
// saying JavaDoc: In the earlier stage, the VideoCapture is deprioritized.
// private val videoCapture: VideoCapture = VideoCapture(
// VideoCaptureConfig.Builder()
// .setVideoFrameRate(60)
// ...
// .build()
// )
private val previewView by lazy {
findViewById<TextureView>(R.id.surfaceView)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
preview.setOnPreviewOutputUpdateListener { output ->
Log.d("Main", "PreviewOutputUpdated: ${output.textureSize}")
previewView.surfaceTexture = output.surfaceTexture
}
imageAnalysis.setAnalyzer { image, rotationDegrees ->
// Log.d("Main", "Analyzer: $image, $rotationDegrees")
// some ml task here...
}
findViewById<Button>(R.id.button).setOnClickListener {
imageCapture.takePicture(File(filesDir, "picture.jpg"), object: ImageCapture.OnImageSavedListener {
override fun onImageSaved(file: File) {
Log.d("Main", "success: $file")
}
override fun onError(useCaseError: ImageCapture.UseCaseError, message: String, cause: Throwable?) {
Log.w("Main", "error: $useCaseError, $message", cause)
}
})
/* or...
imageCapture.takePicture(object: ImageCapture.OnImageCapturedListener(){
override fun onCaptureSuccess(image: ImageProxy?, rotationDegrees: Int) {
super.onCaptureSuccess(image, rotationDegrees)
}
override fun onError(useCaseError: ImageCapture.UseCaseError?, message: String?, cause: Throwable?) {
super.onError(useCaseError, message, cause)
}
})
*/
}
CameraX.bindToLifecycle(this, preview, imageCapture, imageAnalysis)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.