4-5.Android Camera 之其他方式预览图像编码模板(TextureView)

一、Camera

  1. Camera 用于捕获图像和视频

  2. 在 Android 开发的早期阶段,Android 提供 android.hardware.Camera API,开发者用它来访问和控制设备的摄像头硬件

  3. 然而,随着 Android 系统的发展,从 Android 5.0(API 级别 21)开始,Android 引入了一个新的 Camera2 API,以提供更强大和灵活的控制功能


二、Camera 图像预览

1、Util
  • MyCameraTool.java
package com.my.camera.util;

import android.hardware.Camera;
import android.util.Log;

import com.my.camera.entity.CameraIdResult;

import java.util.List;

public class MyCameraTool {

    public static final String TAG = MyCameraTool.class.getSimpleName();

    /**
     * 得到摄像头 Id 对象
     *
     * @return 摄像头 Id 对象,它有前置摄像头 Id 和后置摄像头 Id
     */
    public static CameraIdResult getCameraIdResult() {
        CameraIdResult cameraIdResult = new CameraIdResult();

        int numberOfCameras = Camera.getNumberOfCameras();
        Log.i(TAG, "------------------------------ 摄像头个数:" + numberOfCameras);

        for (int cameraId = 0; cameraId < numberOfCameras; cameraId++) {
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(cameraId, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                Log.i(TAG, "------------------------------ 前置摄像头,cameraId 为:" + cameraId);
                cameraIdResult.setQzCameraId(cameraId);
            }
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                Log.i(TAG, "------------------------------ 后置摄像头,cameraId 为:" + cameraId);
                cameraIdResult.setHzCameraId(cameraId);
            } else {
                Log.i(TAG, "------------------------------ 其他摄像头,cameraId 为:" + cameraId);
            }
        }

        return cameraIdResult;
    }

    /**
     * 根据 SurfaceView 的尺寸和相机支持的预览尺寸来选择最优的预览尺寸
     *
     * @param sizes 相机支持的预览尺寸列表
     * @param w     SurfaceView 的宽度
     * @param h     SurfaceView 的高度
     * @return 最优的预览尺寸,如果没有合适的尺寸则返回 null
     */
    public static Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        if (sizes == null) return null;

        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) h / w;
        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;
        int targetHeight = h;

        // 遍历所有支持的预览尺寸
        for (Camera.Size size : sizes) {

            // 检查宽高比是否接近目标宽高比
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;

            // 计算当前尺寸与目标尺寸的宽度差异
            // 如果差异小于当前最小差异,则更新最优尺寸和最小差异
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // 如果找不到接近目标宽高比的尺寸,则选择最接近目标高度的尺寸
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }

        return optimalSize;
    }

    /**
     * 打印相机参数信息
     *
     * @param parameters 相机参数对象
     */
    public static void showParameters(Camera.Parameters parameters) {
        Camera.Size previewSize = parameters.getPreviewSize();
        Log.i(TAG, "============================== getPreviewSize");
        Log.i(TAG, "---------- " + previewSize.width + " - " + previewSize.height);

        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        Log.i(TAG, "============================== supportedPreviewSizes");
        Log.i(TAG, "============================== supportedPreviewSizes size: " + supportedPreviewSizes.size());
        for (Camera.Size supportedPreviewSize : supportedPreviewSizes) {
            Log.i(TAG, "---------- " + supportedPreviewSize.width + " - " + supportedPreviewSize.height);
        }

        Camera.Size pictureSize = parameters.getPictureSize();
        Log.i(TAG, "============================== getPictureSize");
        Log.i(TAG, "---------- " + pictureSize.width + " - " + pictureSize.height);

        List<Camera.Size> supportedPictureSizes = parameters.getSupportedPictureSizes();
        Log.i(TAG, "============================== getSupportedPictureSizes");
        Log.i(TAG, "============================== getSupportedPictureSizes: " + supportedPictureSizes.size());
        for (Camera.Size supportedPictureSize : supportedPictureSizes) {
            Log.i(TAG, "---------- " + supportedPictureSize.width + " - " + supportedPictureSize.height);
        }

        String focusMode = parameters.getFocusMode();
        Log.i(TAG, "============================== getFocusMode");
        Log.i(TAG,"---------- " + focusMode);

        String whiteBalance = parameters.getWhiteBalance();
        Log.i(TAG, "============================== getWhiteBalance");
        Log.i(TAG,"---------- " + whiteBalance);

        int exposureCompensation = parameters.getExposureCompensation();
        Log.i(TAG, "============================== getExposureCompensation");
        Log.i(TAG,"---------- " + exposureCompensation);

        String flashMode = parameters.getFlashMode();
        Log.i(TAG, "============================== getFlashMode");
        Log.i(TAG,"---------- " + flashMode);
    }
}
2、Activity Layout
  • activity_preview_image_by_texture_view.xml

<androidx.constraintlayout.widget.ConstraintLayout 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=".PreviewImageByTextureViewActivity">

    <TextureView
        android:id="@+id/tv"
        android:layout_width="300dp"
        android:layout_height="300dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
androidx.constraintlayout.widget.ConstraintLayout>
3、Activity Code
  • PreviewImageByTextureViewActivity.java
package com.my.camera;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.WindowManager;

import com.my.camera.entity.CameraIdResult;
import com.my.camera.util.MyCameraTool;

import java.io.IOException;
import java.util.List;

public class PreviewImageByTextureViewActivity extends AppCompatActivity {

    public static final String TAG = PreviewImageByTextureViewActivity.class.getSimpleName();

    private TextureView tv;

    private int hzCameraId;
    private Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_image_by_texture_view);

        // 保持屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        CameraIdResult cameraIdResult = MyCameraTool.getCameraIdResult();
        hzCameraId = cameraIdResult.getHzCameraId();

        tv = findViewById(R.id.tv);
        tv.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                Log.i(TAG, "------------------------------ onSurfaceTextureAvailable");
                openCamera(surface);
                cameraPreview(width, height);
            }

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

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

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
                Log.i(TAG, "------------------------------ onSurfaceTextureUpdated");
            }
        });
    }

    private void openCamera(SurfaceTexture surface) {
        try {
            if (camera != null) return;
            if (hzCameraId == -1) return;
            camera = Camera.open(hzCameraId);
            camera.setPreviewTexture(surface);
            camera.setDisplayOrientation(90);
            camera.setPreviewCallback(new Camera.PreviewCallback() {
                @Override
                public void onPreviewFrame(byte[] data, Camera camera) {
                    Log.i(TAG, "------------------------------ 得到预览帧数据的 size 为 " + data.length);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            closeCamera();
        }
    }

    private void cameraPreview(int width, int height) {
        if (camera == null) return;
        Camera.Parameters parameters = camera.getParameters();
        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        Camera.Size previewSize = MyCameraTool.getOptimalPreviewSize(supportedPreviewSizes, width, height);
        parameters.setPreviewSize(previewSize.width, previewSize.height);
        camera.setParameters(parameters);
        camera.startPreview();
    }

    private void closeCamera() {
        try {
            if (camera == null) return;
            camera.setPreviewCallback(null);
            camera.setPreviewTexture(null);
            camera.stopPreview();
            camera.release();
            camera = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

三、Camera 预览图像案例解析

1、添加权限
  • 在 AndroidManifest.xml 文件中添加相关权限,如果是 Android 6.0(API 级别 23)或之后,需要在运行时请求
<uses-permission android:name="android.permission.CAMERA" />
2、保持屏幕常亮
  • 保持屏幕常亮就是不会自动关闭屏幕,不仅是预览图像,它也非常适用于阅读、视频播放等
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
3、选择摄像头
  • 这里借助工具类,选择后置摄像头 ID,准备使用后置摄像头(手机背后的)
CameraIdResult cameraIdResult = MyCameraTool.getCameraIdResult();
hzCameraId = cameraIdResult.getHzCameraId();
4、准备 TextureView 作为图像预览容器
  • TextureView 控件可用于预览图像、视频播放等
<TextureView
    android:id="@+id/tv"
    android:layout_width="300dp"
    android:layout_height="300dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>
  • 通过 setSurfaceTextureListener 方法来监听 TextureView 的状态变化并进行相应的操作,它接收一个 TextureView.SurfaceTextureListener 实例对象,该对象有 4 个回调方法
  1. onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height):当 TextureView 的 SurfaceTexture 准备好时调用该方法,这里可以收集 SurfaceTexture 对象并打开相机,调整相机预览的尺寸并开始预览

  2. onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height):当 TextureView 的大小发生变化时调用该方法

  3. onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface):当 TextureView 的 SurfaceTexture 被销毁时调用该方法,这里可以关闭相机,返回 true 表示资源已被正确释放

  4. onSurfaceTextureUpdated(@NonNull SurfaceTexture surface):当 SurfaceTexture 的内容更新时调用该方法

tv = findViewById(R.id.tv);
tv.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
        Log.i(TAG, "------------------------------ onSurfaceTextureAvailable");
        openCamera(surface);
        cameraPreview(width, height);
    }

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

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

    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
        Log.i(TAG, "------------------------------ onSurfaceTextureUpdated");
    }
});
5、打开相机
  1. camera = Camera.open(hzCameraId);:通过摄像头 ID 打开摄像头

  2. camera.setPreviewDisplay(surfaceHolder);:将摄像头的预览输出设置到 SurfaceTexture 对象上

  3. camera.setDisplayOrientation(90);:设置预览方向(否则图像不是正向的)

  4. camera.setPreviewCallback(......:注册一个预览回调来接收预览帧数据

private void openCamera(SurfaceTexture surface) {
    try {
        if (camera != null) return;
        if (hzCameraId == -1) return;
        camera = Camera.open(hzCameraId);
        camera.setPreviewTexture(surface);
        camera.setDisplayOrientation(90);
        camera.setPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
                Log.i(TAG, "------------------------------ 得到预览帧数据的 size 为 " + data.length);
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
        closeCamera();
    }
}
6、调整相机预览的尺寸并开始预览
  1. Camera.Parameters parameters = camera.getParameters();:得到相机参数对象

  2. List supportedPreviewSizes = parameters.getSupportedPreviewSizes();:得到支持的预览尺寸列表

  3. camera.setParameters(parameters);:借助工具类选择最优的预览尺寸并设置

  4. camera.startPreview();:开始预览图像

private void cameraPreview(int width, int height) {
    if (camera == null) return;
    Camera.Parameters parameters = camera.getParameters();
    List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
    Camera.Size previewSize = MyCameraTool.getOptimalPreviewSize(supportedPreviewSizes, width, height);
    parameters.setPreviewSize(previewSize.width, previewSize.height);
    camera.setParameters(parameters);
    camera.startPreview();
}
7、关闭相机
  1. camera.setPreviewCallback(null);:移除预览回调

  2. camera.setPreviewTexture(null);:移除 SurfaceTexture 对象

  3. camera.stopPreview();:停止预览图像

  4. camera.release();:释放摄像头资源

private void closeCamera() {
    try {
        if (camera == null) return;
        camera.setPreviewCallback(null);
        camera.setPreviewTexture(null);
        camera.stopPreview();
        camera.release();
        camera = null;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(Android,-,简化编程,android,java,java-ee,android-studio,android,studio,安卓)