Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I lock/freeze a CameraX preview TextureView?

I'm following the CameraX code lab and also looked at their sample app and source code in Android Studio, but there doesn't seem to be a way to freeze or lock the TextureView that is showing the preview frames.

In the Camera2 API we can just call something like cameraCaptureSession?.stopRepeating() and the TextureView will stop getting input from the camera.

My use case for freezing the preview is to show the user the image that is currently being saved as I add other animations on top of the TextureView.

like image 308
Chee-Yi Avatar asked May 21 '19 12:05

Chee-Yi


2 Answers

// You can unbind from any UseCase
CameraX.unbind(previewUseCase)
// In this way TextureView will hold the last frame


 // for version 1.0.0-alpha07
 cameraProvider.unbind(preview);
like image 177
yevhen_69 Avatar answered Oct 23 '22 03:10

yevhen_69


You can use PreviewView.getBitmap() to capture the latest image that appears on the preview screen. It is very quick and you don't even have to rotate or flip the image.

my XML code:

        <androidx.camera.view.PreviewView
            android:id="@+id/viewFinder"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="3:3"
            app:layout_constraintTop_toTopOf="parent"/>

        <ImageView
            android:visibility="gone"
            android:id="@+id/ivPreview"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="3:3"
            app:layout_constraintTop_toTopOf="parent"/>

my previous code, processing the image from OnImageCapturedCallback or OnImageSavedCallback :

private fun showCapturedImage(bitmap: Bitmap, rotationDegrees: Float) {
        viewFinder.visibility = View.GONE
        ivPreview.visibility = View.VISIBLE
        var rotatedBitmap = ImageUtils.rotateImage(bitmap, rotationDegrees).toSquare()
        if (isTakeFacePhoto){
            rotatedBitmap = rotatedBitmap.flipBitmap()
        }
        ivPreview.setImageBitmap(rotatedBitmap)
    }

current code, after using PreviewView.getBitmap() :

val bitmap = viewFinder.getBitmap()

showCapturedImage(bitmap)

private fun showCapturedImage(bitmap: Bitmap) {
           viewFinder.visibility = View.GONE
           ivPreview.visibility = View.VISIBLE
           ivPreview.setImageBitmap(bitmap)
}

If you plan to save your image using OnImageSavedCallback, keep in mind that there might be a slight delay from PreviewView.getBitmap() and the saved file from OnImageSavedCallback so these two images can be really different depends on the delay.

like image 21
moonLander_ Avatar answered Oct 23 '22 04:10

moonLander_