Android camera2實現預覽

lethe1203發表於2024-03-16
Android camera2介面實現camera基礎預覽apk:
1、再AndroidManifest.xml中新增許可權
<uses-permission android:name="android.permission.CAMERA"/>

2、建立一個xml包含控制元件TextureView

比如activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextureView
        android:id="@+id/textureView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="0.8dp"
        android:text="stop preview"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"/>
    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="0.8dp"
        android:text="start preview"
        android:layout_alignParentBottom="true"
        android:layout_toStartOf="@id/btnStop"/>

</RelativeLayout>
3、在Activity建立使用 CamaerManager
  • 使用 CamaerManager.openCamera(),傳入監聽openState狀態
  • 在openState狀態裡面執行預覽介面即可
  • 關閉預覽框的時候釋放一下物件就行
比如下面的MainActivity2.java程式碼:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

/**
 * 本類使用Camera2使用簡單相機
 */
public class MainActivity2 extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "Camera2Test";
    private static final int REQUEST_CAMERA_PERMISSION = 80;
    private TextureView mTextureView;
    private Button mBtnStart;
    private Button mBtnStop;
    private CameraManager mCameraManager;
    private CameraDevice mCameraDevice;
    private String mCameraId = "0";
    private Size previewSize; // 用於設定預覽的寬高

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate!");
        setContentView(R.layout.activity_main);
        initData();
        intiView();
        initEvent();
    }

    private void intiView() {
        mTextureView = (TextureView) findViewById(R.id.textureView);
        mBtnStart = (Button) findViewById(R.id.btnStart);
        mBtnStop = (Button) findViewById(R.id.btnStop);
    }

    private void initData() {
        mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        if (mCameraManager == null) {
            Toast.makeText(this, "獲取不到CameraService物件!", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void initEvent() {
        mBtnStart.setOnClickListener(this);
        mBtnStop.setOnClickListener(this);

        // 對預覽View的狀態監聽
        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                Log.i(TAG, "onSurfaceTextureAvailable width = " + width + ",height = " + height);
                //1、當SurefaceTexture可用的時候,設定相機引數並開啟相機
                initCamera();
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
                Log.i(TAG, "onSurfaceTextureSizeChanged width = " + width + ",height = " + height);
            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                Log.i(TAG, "onSurfaceTextureDestroyed!");
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
                //正常預覽的時候,會一直列印
                //Log.i(TAG, "onSurfaceTextureUpdated!");
            }
        });
    }


    private void initCamera() {
        Log.i(TAG, "initCamera");
        // 2.配置前置相機,獲取尺寸及id
        getCameraIdAndPreviewSizeByFacing(CameraCharacteristics.LENS_FACING_FRONT); // 0為前置攝像頭,Camera api1裡面定義0為後置
        // 3.開啟相機
        openCamera();
    }


    /*獲取cameraId及相機預覽的最佳尺寸*/
    private void getCameraIdAndPreviewSizeByFacing(int lensFacingFront) {
        Log.i(TAG, "getCameraIdAndPreviewSizeByFacing");
        try {
            String[] cameraIdList = mCameraManager.getCameraIdList(); //如果裝置節點不可用,會阻塞在這裡
            Log.i(TAG, "getCameraIdAndPreviewSizeByFacing cameraIdList = " + Arrays.toString(cameraIdList));
            for (String cameraId : cameraIdList) {

                CameraCharacteristics cameraCharacteristics = mCameraManager.getCameraCharacteristics(cameraId);
                int deviceLevel = cameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); //硬體與api2的契合度,0-4
                Log.i(TAG, "deviceLevel = " + deviceLevel);
                int facing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != lensFacingFront) {
                    continue;
                }
                StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                Size[] outputSizes = streamConfigurationMap.getOutputSizes(SurfaceTexture.class);
                mCameraId = cameraId;
                previewSize = setOptimalPreviewSize(outputSizes, mTextureView.getMeasuredWidth(), mTextureView.getMeasuredHeight());
                Log.i(TAG, "最佳預覽尺寸(w-h):" + previewSize.getWidth() + "-" + previewSize.getHeight() + ",相機id:" + mCameraId);

            }
        } catch (CameraAccessException e) {
            Log.e(TAG, "getCameraIdAndPreviewSizeByFacing error = " + e.getMessage());
        }
    }

    /**
     * 開啟相機,預覽是在回撥裡面執行的。
     */
    private void openCamera() {
        try {
            // 4.許可權檢查
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                requestCameraPermission();
                return;
            }

            // 5.真正開啟相機
            Log.i(TAG, "openCamera");
            mCameraManager.openCamera(mCameraId, mStateCallback, null);
        } catch (CameraAccessException e) {
            Log.e(TAG, "openCamera error = " + e.getMessage());
        }

    }

    //請求相機許可權
    private void requestCameraPermission() {
        requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
    }

    /**
     * 根據相機可用的預覽尺寸和使用者給定的TextureView的顯示尺寸選擇最接近的預覽尺寸
     */
    private Size setOptimalPreviewSize(Size[] sizes, int previewViewWidth, int previewViewHeight) {
        List<Size> bigEnoughSizes = new ArrayList<>();
        List<Size> notBigEnoughSizes = new ArrayList<>();
        for (Size size : sizes) {
            if (size.getWidth() >= previewViewWidth && size.getHeight() >= previewViewHeight) {
                bigEnoughSizes.add(size);
            } else {
                notBigEnoughSizes.add(size);
            }
        }
        if (bigEnoughSizes.size() > 0) {
            return Collections.min(bigEnoughSizes, new Comparator<Size>() {
                @Override
                public int compare(Size lhs, Size rhs) {
                    return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                            (long) rhs.getWidth() * rhs.getHeight());
                }
            });
        } else if (notBigEnoughSizes.size() > 0) {
            return Collections.max(notBigEnoughSizes, new Comparator<Size>() {
                @Override
                public int compare(Size lhs, Size rhs) {
                    return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                            (long) rhs.getWidth() * rhs.getHeight());
                }
            });
        } else {
            Log.e(TAG, "未找到合適的預覽尺寸");
            return sizes[0];
        }
    }

    //關閉相機,釋放物件
    private void releaseCamera() {
        if (mCameraDevice != null) {
            mCameraDevice.close();
            mCameraDevice = null;
        }
    }

    /**
     * 相機狀態監聽物件
     */
    private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            Log.i(TAG, "StateCallback! onOpened");
            mCameraDevice = camera; // 開啟成功,儲存代表相機的CameraDevice例項
            SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
            surfaceTexture.setDefaultBufferSize(mTextureView.getWidth(), mTextureView.getHeight());
            Surface surface = new Surface(surfaceTexture);
            ArrayList<Surface> previewList = new ArrayList<>();
            previewList.add(surface);
            try {
                // 6.將TextureView的surface傳遞給CameraDevice
                mCameraDevice.createCaptureSession(previewList, new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        try {
                            CaptureRequest.Builder builder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                            builder.addTarget(surface); // 必須設定才能正常預覽
                            CaptureRequest captureRequest = builder.build();

                            // 7.CameraCaptureSession與CaptureRequest繫結(這是最後一步,已可顯示相機預覽)
                            session.setRepeatingRequest(captureRequest, mSessionCaptureCallback, null);
                        } catch (CameraAccessException e) {
                            Log.e(TAG, "createCaptureRequest error = " + e.getMessage());
                        }
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                        Log.e(TAG, "onConfigureFailed");
                    }
                }, null);
            } catch (CameraAccessException e) {
                Log.e(TAG, "createCaptureSession error = " + e.getMessage());
            }
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            Log.e(TAG, "StateCallback! onDisconnected camera.getId() = " + camera.getId());
            releaseCamera();
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            Log.e(TAG, "StateCallback camera.getId() = " + camera.getId() + " , error = " + error);
            releaseCamera();
        }
    };

    //預覽情況回撥
    private CameraCaptureSession.CaptureCallback mSessionCaptureCallback = new CameraCaptureSession.CaptureCallback() {
        @Override
        public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
            super.onCaptureStarted(session, request, timestamp, frameNumber);
            // 正常預覽會一直重新整理
            //Log.i(TAG, "mSessionCaptureCallback onCaptureStarted frameNumber =" + frameNumber);
        }

        @Override
        public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request, CaptureResult partialResult) {
            super.onCaptureProgressed(session, request, partialResult);
            Log.i(TAG, "mSessionCaptureCallback onCaptureProgressed request =" + request);
        }

        @Override
        public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
            super.onCaptureFailed(session, request, failure);
            Log.e(TAG, "mSessionCaptureCallback onCaptureFailed request =" + request);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
            super.onCaptureCompleted(session, request, result);
            // 正常預覽時會一直重新整理
            //Log.i(TAG, "mSessionCaptureCallback onCaptureCompleted request =" + request);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnStart:
                Log.i(TAG, "btnStart!");
                openCamera();
                break;
            case R.id.btnStop:
                Log.i(TAG, "btnStop!");
                releaseCamera();
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseCamera();
    }
}

相關文章