前言
Camera1 在 API 21 的时候已经被弃用了,虽然现在google 都推荐 使用 Camerax 来实现相机的一些功能,但这不妨碍我们学习 Camera1 和 Camera2,对此有基础了解,为后续学习 Camera2 和 Camerax 做铺垫
本篇文章,你将学习到:
- 实现相机的开启与预览
- 调整预览方向
- 切换摄像头
- 拍照及调整图片方向
一、实现相机的开启与预览
1. 效果图
2. 在清单文件中申请权限
<uses-permission android:name="android.permission.CAMERA" /><!-- 支持相机才能运行 --><uses-featureandroid:name="android.hardware.camera"android:required="true" />
3. 在 Java 代码中添加运行时权限授权,在 Activity 的 onCreate 函数中添加如下代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);}}
4. 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><com.hjq.bar.TitleBarandroid:id="@+id/title_bar"android:layout_width="match_parent"android:background="@color/teal_200"android:layout_height="?android:attr/actionBarSize"app:title="Camera1 使用"app:titleStyle="bold"app:titleSize="18sp"app:backButton="false"app:titleColor="@color/white"/><androidx.constraintlayout.widget.ConstraintLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"><SurfaceViewandroid:id="@+id/surface"android:layout_width="0dp"android:layout_height="0dp"app:layout_constraintTop_toTopOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintDimensionRatio="H,3:4"/><Buttonandroid:id="@+id/btn_trans"android:layout_width="wrap_content"android:layout_height="wrap_content"app:layout_constraintTop_toBottomOf="@id/surface"app:layout_constraintTop_toTopOf="parent"app:layout_constraintStart_toStartOf="parent"android:layout_margin="10dp"android:text="切换摄像头"/><Buttonandroid:id="@+id/btn_takePhoto"android:layout_width="wrap_content"android:layout_height="wrap_content"app:layout_constraintTop_toBottomOf="@id/surface"app:layout_constraintStart_toStartOf="parent"app:layout_constraintEnd_toEndOf="parent"android:text="拍照"/></androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
5. 获取相机个数
一般手机中,都有前置摄像头和后置摄像头,我们可以根据 Camera 的 getNumberOfCameras() 方法,来获取这些信息。比如:
/*** 初始化相机*/private void initCamera() {//获取相机个数int numberOfCameras = Camera.getNumberOfCameras();for (int i = 0; i < numberOfCameras; i++) {Camera.CameraInfo info = new Camera.CameraInfo();//获取相机信息Camera.getCameraInfo(i, info);//前置摄像头if (Camera.CameraInfo.CAMERA_FACING_FRONT == info.facing) {mFrontCameraId = i;mFrontCameraInfo = info;} else if (Camera.CameraInfo.CAMERA_FACING_BACK == info.facing) {mBackCameraId = i;mBackCameraInfo = info;}}}
通过 Camera.getCameraInfo(i, info)
就可以拿到当前的 CameraInfo
的信息,里面有个参数我们需要注意一下,就是 facing
,它表示当前摄像机面对的方向,理解为前置和后置,然后我们把这些信息也保存起来。
6. 打开摄像头
使用 Camera.open(cameraid) 去打开摄像头
//根据 cameraId 打开不同摄像头,注意,Camera1只有打开摄像头之后,才能拿到那些配置数据mCamera = Camera.open(cameraId);
7. 配置摄像头属性
在开启相机预览之前,我们需要对相机进行一些参数配置,比如聚焦,预览尺寸等;这里我使用的是 SurfaceView,所以等 SurfaceView 创建好之后,可以对它进行一些参数的设置:
@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {startPreview(width, height);}.../*** 开始显示*/private void startPreview(int width, int height) {initPreviewParams(width, height);//设置预览 SurfaceHolderCamera camera = mCamera;if (camera != null) {try {camera.setPreviewDisplay(mSurfaceView.getHolder());} catch (IOException e) {e.printStackTrace();}}//开始显示camera.startPreview();}
在 Camera中,我们可以通过 camera.getParameters() 拿到相机默认的参数,如果要配置自己的参数,可以使用 camera.setParameters(parameters) 去设置,不过这个比较比较好使,所以相机的配置开启这些,可以使用 HandlerThread 去开启,这里就不增加多余代码了。
initPreviewParams 的完整代码如下:
/*** 设置预览参数,需要制定尺寸才行* 在相机中,width > height 的,而我们的UI是3:4,所以这里也要做换算** @param shortSize* @param longSize*/private void initPreviewParams(int shortSize, int longSize) {Camera camera = mCamera;if (camera != null) {Camera.Parameters parameters = camera.getParameters();//获取手机支持的尺寸List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();Camera.Size bestSize = getBestSize(shortSize, longSize, sizes);//设置预览大小parameters.setPreviewSize(bestSize.width, bestSize.height);//设置图片大小,拍照parameters.setPictureSize(bestSize.width, bestSize.height);//设置格式parameters.setPreviewFormat(ImageFormat.NV21);//设置自动聚焦List<String> modes = parameters.getSupportedFocusModes();//查看支持的聚焦模式for (String mode : modes) {//默认图片聚焦模式if (mode.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);break;}}camera.setParameters(parameters);}}
8. 相机预览大小
首先,应该根据自己UI的大小去设置相机预览的大小,如果你的控件为 200x200,但相机的数据为 1920x1080 ,这样填充过去,画面肯定是会被拉伸的。
List<Camera.Size> sizes = parameters.getSupportedPreviewSizes()
注意相机的 width > height,所以获取一个最佳的预览尺寸可以这样写:
/*** 获取预览最后尺寸** @param shortSize* @param longSize* @param sizes* @return*/private Camera.Size getBestSize(int shortSize, int longSize, List<Camera.Size> sizes) {Camera.Size bestSize = null;float uiRatio = (float) longSize / shortSize;float minRatio = uiRatio;for (Camera.Size previewSize : sizes) {float cameraRatio = (float) previewSize.width / previewSize.height;//如果找不到比例相同的,找一个最近的,防止预览变形float offset = Math.abs(cameraRatio - minRatio);if (offset < minRatio) {minRatio = offset;bestSize = previewSize;}//比例相同if (uiRatio == cameraRatio) {bestSize = previewSize;break;}}return bestSize;}
二、调整预览方向
在调整预览方向前,我们需要先了解一些知识。
- 屏幕坐标: Android 坐标系中,在 (0,0) 坐标那,向右为 x 轴,向下为 y 轴。
- 自然方向: 设置的自然方向,比如手机默认就是竖直是自然方向,平板的话,横向就是自然方向
- 图片传感器方向: 手机的图片数据都来自摄像头硬件传感器,这个传感器有个默认的方向,一般是手机是横向的,这就跟手机的自然方向成 90° 关系了。
方向调整代码可以这样写:
/*** 矫正相机预览画面** @param info*/private void adjustCameraOrientation(Camera.CameraInfo info) {//判断当前的横竖屏int rotation = getWindowManager().getDefaultDisplay().getRotation();int degress = 0;//获取手机的方向switch (rotation) {case Surface.ROTATION_0:degress = 0;break;case Surface.ROTATION_90:degress = 90;break;case Surface.ROTATION_180:degress = 180;break;case Surface.ROTATION_270:degress = 270;break;}int result = 0;//后置摄像头if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {result = (info.orientation - degress + 360) % 360;} else if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//先镜像result = (info.orientation + degress) % 360;result = (360 - result) % 360;}mCamera.setDisplayOrientation(result);}
三、切换摄像头
现在用到的都是后置摄像头,切换也比较简单,首先先释放相机支援,然后再从配置参数,预览再来一遍即可:
//关闭摄像头closeCamera();mCameraID = mCameraID == mFrontCameraId ? mBackCameraId : mFrontCameraId;//打开相机openCamera(mCameraID);//开启预览startPreview(mSurfaceView.getWidth(), mSurfaceView.getHeight());.../*** 关闭摄像头*/private void closeCamera() {//停止预览if (mCamera != null) {mCamera.stopPreview();mCamera.release();mCamera = null;}}
四、拍照及调整图片方向
Camera
的拍照也比较简单,使用 takePicture(ShutterCallback shutter, PictureCallback raw, PictureCallback jpeg)
方法即可,它的三个参数如下:
ShutterCallback
:拍照瞬间调用,如果空回调,则由声音,传 null ,则没效果PictureCallback
:图片的原始数据,即没处理过的PictureCallback
: 图片的 JPEG 数据
拿到 byte 数据后,转换成 bitmap 即可,如下:
Camera camera = mCamera;
camera.takePicture(new Camera.ShutterCallback() {@Overridepublic void onShutter() {}
}, null, new Camera.PictureCallback() {@Overridepublic void onPictureTaken(byte[] data, Camera camera) {new SavePicAsyncTask(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);}
});
这里的图片保存,用一个 AsyncTask 来保存:
/*** 保存图片*/class SavePicAsyncTask extends AsyncTask<Void, Void, File> {byte[] data;File file;public SavePicAsyncTask(byte[] data) {this.data = data;File dir = new File(GlobalConfig.PATH);if (!dir.exists()) {dir.mkdirs();}String name = "test.jpg";file = new File(dir, name);}@Overrideprotected File doInBackground(Void... voids) {Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);if (bitmap == null) {return null;}FileOutputStream fos = null;try {fos = new FileOutputStream(file);//保存之前先调整方向Camera.CameraInfo info = mCameraID == mFrontCameraId ? mFrontCameraInfo : mBackCameraInfo;if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {bitmap = BitmapUtils.rotate(bitmap, 90);} else {bitmap = BitmapUtils.rotate(bitmap, 270);bitmap = BitmapUtils.mirror(bitmap);}bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);} catch (FileNotFoundException e) {e.printStackTrace();} finally {CloseUtils.close(fos);}return file;}@Overrideprotected void onPostExecute(File file) {super.onPostExecute(file);if (file != null) {Toast.makeText(MainActivity.this, "图片保存成功", Toast.LENGTH_SHORT).show();} else {Toast.makeText(MainActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();}}}
注意:保持路径代码。
public static final String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CameraDemo";
五、完整代码
- CloseUtils.java
public class CloseUtils {public static void close(Closeable... closeables){if (closeables != null) {for (Closeable closeable : closeables) {if (closeable != null) {try {closeable.close();} catch (IOException e) {e.printStackTrace();}}}}}
}
- BitmapUtils.java
public class BitmapUtils {/*** 镜像* @param bitmap* @return*/public static Bitmap mirror(Bitmap bitmap){Matrix matrix = new Matrix();matrix.postScale(-1f,1f);return Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);}/*** 旋转图片* @param bitmap* @param degress* @return*/public static Bitmap rotate(Bitmap bitmap,float degress){Matrix matrix = new Matrix();matrix.postRotate(degress);return Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);}
}
- MainActivity.java
public class MainActivity extends BaseActivity {@BindView(R.id.surface)SurfaceView mSurfaceView;private int mFrontCameraId;private int mBackCameraId;private Camera.CameraInfo mFrontCameraInfo;private Camera.CameraInfo mBackCameraInfo;private Camera mCamera;private int mCameraID;@Overrideprotected int getLayoutId() {return R.layout.activity_main;}@Overrideprotected void initView() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {requestPermissions(new String[] {Manifest.permission.CAMERA}, 1);}}initCamera();//打开摄像头openCamera(mBackCameraId);}/*** 初始化相机*/private void initCamera() {//获取相机个数int numberOfCameras = Camera.getNumberOfCameras();for (int i = 0; i < numberOfCameras; i++) {Camera.CameraInfo info = new Camera.CameraInfo();//获取相机信息Camera.getCameraInfo(i, info);//前置摄像头if (Camera.CameraInfo.CAMERA_FACING_FRONT == info.facing) {mFrontCameraId = i;mFrontCameraInfo = info;} else if (Camera.CameraInfo.CAMERA_FACING_BACK == info.facing) {mBackCameraId = i;mBackCameraInfo = info;}}}@Overrideprotected void onResume() {super.onResume();if (mSurfaceView != null && mSurfaceView.getWidth() != 0){openCamera(mCameraID);startPreview(mSurfaceView.getWidth(),mSurfaceView.getHeight());}else{mSurfaceView.getHolder().addCallback(new PreviewCallback());}}/*** 开始显示*/private void startPreview(int width, int height) {initPreviewParams(width, height);//设置预览 SurfaceHolderCamera camera = mCamera;if (camera != null) {try {camera.setPreviewDisplay(mSurfaceView.getHolder());} catch (IOException e) {e.printStackTrace();}}//开始显示camera.startPreview();}/*** 打开摄像头** @param cameraId*/private void openCamera(int cameraId) {//根据 cameraId 打开不同摄像头,注意,Camera1只有打开摄像头之后,才能拿到那些配置数据mCamera = Camera.open(cameraId);mCameraID = cameraId;Camera.CameraInfo info = cameraId == mFrontCameraId ? mFrontCameraInfo : mBackCameraInfo;adjustCameraOrientation(info);}/*** 矫正相机预览画面** @param info*/private void adjustCameraOrientation(Camera.CameraInfo info) {//判断当前的横竖屏int rotation = getWindowManager().getDefaultDisplay().getRotation();int degress = 0;//获取手机的方向switch (rotation) {case Surface.ROTATION_0:degress = 0;break;case Surface.ROTATION_90:degress = 90;break;case Surface.ROTATION_180:degress = 180;break;case Surface.ROTATION_270:degress = 270;break;}int result = 0;//后置摄像头if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {result = (info.orientation - degress + 360) % 360;} else if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//先镜像result = (info.orientation + degress) % 360;result = (360 - result) % 360;}mCamera.setDisplayOrientation(result);}/*** 设置预览参数,需要制定尺寸才行* 在相机中,width > height 的,而我们的UI是3:4,所以这里也要做换算** @param shortSize* @param longSize*/private void initPreviewParams(int shortSize, int longSize) {Camera camera = mCamera;if (camera != null) {Camera.Parameters parameters = camera.getParameters();//获取手机支持的尺寸List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();Camera.Size bestSize = getBestSize(shortSize, longSize, sizes);//设置预览大小parameters.setPreviewSize(bestSize.width, bestSize.height);//设置图片大小,拍照parameters.setPictureSize(bestSize.width, bestSize.height);//设置格式parameters.setPreviewFormat(ImageFormat.NV21);//设置自动聚焦List<String> modes = parameters.getSupportedFocusModes();//查看支持的聚焦模式for (String mode : modes) {//默认图片聚焦模式if (mode.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)){parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);break;}}camera.setParameters(parameters);}}/*** 获取预览最后尺寸** @param shortSize* @param longSize* @param sizes* @return*/private Camera.Size getBestSize(int shortSize, int longSize, List<Camera.Size> sizes) {Camera.Size bestSize = null;float uiRatio = (float) longSize / shortSize;float minRatio = uiRatio;for (Camera.Size previewSize : sizes) {float cameraRatio = (float) previewSize.width / previewSize.height;//如果找不到比例相同的,找一个最近的,防止预览变形float offset = Math.abs(cameraRatio - minRatio);if (offset < minRatio) {minRatio = offset;bestSize = previewSize;}//比例相同if (uiRatio == cameraRatio) {bestSize = previewSize;break;}}return bestSize;}@Overrideprotected void onPause() {super.onPause();closeCamera();}@OnClick({R.id.btn_trans,R.id.btn_takePhoto})public void clicked(View view) {switch (view.getId()) {case R.id.btn_trans://关闭摄像头closeCamera();mCameraID = mCameraID == mFrontCameraId ? mBackCameraId : mFrontCameraId;//打开相机openCamera(mCameraID);//开启预览startPreview(mSurfaceView.getWidth(), mSurfaceView.getHeight());break;case R.id.btn_takePhoto:Camera camera = mCamera;camera.takePicture(new Camera.ShutterCallback() {@Overridepublic void onShutter() {}}, null, new Camera.PictureCallback() {@Overridepublic void onPictureTaken(byte[] data, Camera camera) {new SavePicAsyncTask(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);}});break;}}/*** 保存图片*/class SavePicAsyncTask extends AsyncTask<Void, Void, File> {byte[] data;File file;public SavePicAsyncTask(byte[] data) {this.data = data;File dir = new File(GlobalConfig.PATH);if (!dir.exists()) {dir.mkdirs();}String name = "test.jpg";file = new File(dir, name);}@Overrideprotected File doInBackground(Void... voids) {Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);if (bitmap == null) {return null;}FileOutputStream fos = null;try {fos = new FileOutputStream(file);//保存之前先调整方向Camera.CameraInfo info = mCameraID == mFrontCameraId ? mFrontCameraInfo : mBackCameraInfo;if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {bitmap = BitmapUtils.rotate(bitmap, 90);} else {bitmap = BitmapUtils.rotate(bitmap, 270);bitmap = BitmapUtils.mirror(bitmap);}bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);} catch (FileNotFoundException e) {e.printStackTrace();} finally {CloseUtils.close(fos);}return file;}@Overrideprotected void onPostExecute(File file) {super.onPostExecute(file);if (file != null) {Toast.makeText(MainActivity.this, "图片保存成功", Toast.LENGTH_SHORT).show();} else {Toast.makeText(MainActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();}}}/*** 关闭摄像头*/private void closeCamera() {//停止预览if (mCamera != null) {mCamera.stopPreview();mCamera.release();mCamera = null;}}class PreviewCallback implements SurfaceHolder.Callback {@Overridepublic void surfaceCreated(SurfaceHolder holder) {}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {startPreview(width, height);}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {}}@Overrideprotected void onDestroy() {super.onDestroy();closeCamera();}}