Android implements camera (Camera) preview

CameraX is a Jetpack library designed to help you develop camera applications more easily. For new applications, we recommend starting with CameraX. It provides a consistent and easy-to-use API for the vast majority of Android devices and is backward compatible with Android 5.0 (API level 21).

CameraX supports most common camera use cases:
  • 预览: View the picture on the screen.
  • 图片分析: Seamlessly access images in buffers for use in algorithms, such as passing them to machine learning suites.
  • 图片拍摄:save Picture.
  • 视频拍摄: Save video and audio.

This article is about –实现预览

When adding previews to your app, use PreviewView, a View that can be clipped, scaled, and rotated to ensure proper display.
When the camera is active, the image preview is streamed to the Surface in PreviewView.

renderings

Configuration:

  • 注意:CameraX 支持的最小SDK版本是21
    insert image description here
  • 1. Add permissions

1. Add camera permissions to the manifest file

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

2. Dynamically obtain camera permissions

  if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
    
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    
                requestPermissions(new String[]{
    
    Manifest.permission.CAMERA}, 11);
            }
        } else {
    
    
            //启动相机 
        }
  • 2. Add CameraX dependency in build.gradle
    implementation "androidx.camera:camera-core:1.1.0-alpha10"
// CameraX Camera2 extensions[可选]拓展库可实现人像、HDR、夜间和美颜、滤镜但依赖于OEM
    implementation "androidx.camera:camera-camera2:1.1.0-alpha10"
// CameraX Lifecycle library[可选]避免手动在生命周期释放和销毁数据
    implementation "androidx.camera:camera-lifecycle:1.1.0-alpha10"
// CameraX View class[可选]最佳实践,最好用里面的PreviewView,它会自行判断用SurfaceView还是TextureView来实现
    implementation 'androidx.camera:camera-view:1.0.0-alpha23'

Use PreviewView case steps:

1. (Optional) Configure CameraXConfig.Provider.
2. Add PreviewView to the layout.
3. Request ProcessCameraProvider.
4. When creating View, please check ProcessCameraProvider.
5. Select the camera and bind the life cycle and use case.

  • Add PreviewView to layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <FrameLayout
        android:layout_centerInParent="true"
        android:layout_width="500dp"
        android:layout_height="500dp">
        <androidx.camera.view.PreviewView
            android:id="@+id/previewView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </FrameLayout>
</RelativeLayout>
  • Steps 3, 4, 5, processing
package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;


public class MainActivity extends AppCompatActivity {
    
    
    
    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private PreviewView previewView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        previewView=findViewById(R.id.previewView);//初始化
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
    
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    
    
                requestPermissions(new String[]{
    
    Manifest.permission.CAMERA}, 11);
            }
        } else {
    
    
            //启动相机
            startCamera();
        }
    }

    private void startCamera() {
    
    
        // 请求 CameraProvider
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        //检查 CameraProvider 可用性,验证它能否在视图创建后成功初始化
        cameraProviderFuture.addListener(() -> {
    
    
            try {
    
    
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
    
    
                // No errors need to be handled for this Future.
                // This should never be reached.
            }
        }, ContextCompat.getMainExecutor(this));
    }
    //选择相机并绑定生命周期和用例
    private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
    
    
        Preview preview = new Preview.Builder()
                .build();

        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();

        preview.setSurfaceProvider(previewView.getSurfaceProvider());

        Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview);
    }
}
  • At the step of bindPreview, the camera preview has been displayed, please check

Guess you like

Origin blog.csdn.net/afufufufu/article/details/128284159