Skip to content

Instantly share code, notes, and snippets.

@keima
Last active April 18, 2020 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keima/3b7bd4c25d0a098da83e08648ba50be0 to your computer and use it in GitHub Desktop.
Save keima/3b7bd4c25d0a098da83e08648ba50be0 to your computer and use it in GitHub Desktop.
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)
}
}
@AlexanderMatveev
Copy link

Not working in 1.0.0-beta03. They changed everything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment