前面幾篇文章實現了相機的預覽,對預覽中出現的問題及須要注意的事項進行了梳理。java
本篇文章對相機的拍照流程、拍照方向及屏幕旋轉時的適配問題進行梳理。android
這裏選擇最大的相機輸出尺寸做爲拍照尺寸和預覽尺寸。git
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initCamera();
initViews(view);
}
private void initCamera() {
cameraManager = CameraUtils.getInstance().getCameraManager();
cameraId = CameraUtils.getInstance().getBackCameraId();
outputSizes = CameraUtils.getInstance().getCameraOutputSizes(cameraId, SurfaceTexture.class);
photoSize = outputSizes.get(0);
}
private void initViews(View view) {
btnPhoto = view.findViewById(R.id.btn_photo);
btnPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takePhoto();
}
});
previewView = view.findViewById(R.id.preview_view);
}
複製代碼
在 fragment 的 onResume 生命週期函數中啓動相機,在 onPause 中釋放相機。github
@Override
public void onResume() {
super.onResume();
if (previewView.isAvailable()) {
openCamera();
} else {
previewView.setSurfaceTextureListener(surfaceTextureListener);
}
}
@Override
public void onPause() {
releaseCamera();
super.onPause();
}
複製代碼
啓動相機時須要根據此時屏幕的顯示方向(橫屏/豎屏)調整預覽窗口的大小和顯示方向。session
@SuppressLint("MissingPermission")
private void openCamera() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestCameraPermission();
} else {
try {
//根據屏幕的顯示方向調整預覽窗口大小
displayRotation = ((Activity) getContext()).getWindowManager().getDefaultDisplay().getOrientation();
if (displayRotation == Surface.ROTATION_0 || displayRotation == Surface.ROTATION_180) {
previewView.setAspectRation(photoSize.getHeight(), photoSize.getWidth());
}else {
previewView.setAspectRation(photoSize.getWidth(), photoSize.getHeight());
}
//根據屏幕的顯示方向調整預覽方向
configureTransform(previewView.getWidth(), previewView.getHeight());
cameraManager.openCamera(cameraId, cameraStateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
Log.d(TAG, "相機訪問異常");
}
}
}
private void configureTransform(int viewWidth, int viewHeight) {
Activity activity = getActivity();
if (null == previewView || null == photoSize || null == activity) {
return;
}
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
Matrix matrix = new Matrix();
RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
RectF bufferRect = new RectF(0, 0, photoSize.getHeight(), photoSize.getWidth());
float centerX = viewRect.centerX();
float centerY = viewRect.centerY();
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
float scale = Math.max(
(float) viewHeight / photoSize.getHeight(),
(float) viewWidth / photoSize.getWidth());
matrix.postScale(scale, scale, centerX, centerY);
matrix.postRotate(90 * (rotation - 2), centerX, centerY);
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180, centerX, centerY);
}
previewView.setTransform(matrix);
}
複製代碼
surfaceTextureListener 以前的文章也提過,這裏給出代碼app
TextureView.SurfaceTextureListener surfaceTextureListener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//啓動相機
openCamera();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
configureTransform(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
};
複製代碼
還有相機打開的狀態回調監聽,成功打開後,初始化預覽、拍照用的Surface 以及 保存拍照數據用的 ImageReader。ide
CameraDevice.StateCallback cameraStateCallback = new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
Log.d(TAG, "相機已啓動");
//初始化拍照用的 ImageReader 和 Surface
initReaderAndSurface();
cameraDevice = camera;
try {
//初始化預覽 Surface
SurfaceTexture surfaceTexture = previewView.getSurfaceTexture();
if (surfaceTexture == null){
return;
}
surfaceTexture.setDefaultBufferSize(photoSize.getWidth(), photoSize.getHeight());//設置SurfaceTexture緩衝區大小
previewSurface = new Surface(surfaceTexture);
previewRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
previewRequestBuilder.addTarget(previewSurface);
previewRequest = previewRequestBuilder.build();
cameraDevice.createCaptureSession(Arrays.asList(previewSurface, photoSurface), sessionsStateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
Log.d(TAG, "相機訪問異常");
}
}
@Override
public void onDisconnected(CameraDevice camera) {
Log.d(TAG, "相機已斷開鏈接");
}
@Override
public void onError(CameraDevice camera, int error) {
Log.d(TAG, "相機打開出錯");
}
};
複製代碼
須要注意的是別忘了給 ImageReader 添加監聽器。 當拍照數據可用時會回調該監聽,在監聽的回調方法中,添加圖片的處理保存邏輯便可。函數
private void initReaderAndSurface() {
//初始化拍照 ImageReader
photoReader = ImageReader.newInstance(photoSize.getWidth(), photoSize.getHeight(), ImageFormat.JPEG, 2);
photoReader.setOnImageAvailableListener(photoReaderImgListener, null);
photoSurface = photoReader.getSurface();
}
ImageReader.OnImageAvailableListener photoReaderImgListener = new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
writeImageToFile();
}
};
private void writeImageToFile() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestStoragePermission();
} else {
String filePath = Environment.getExternalStorageDirectory() + "/DCIM/Camera/001.jpg";
Image image = photoReader.acquireNextImage();
if (image == null) {
return;
}
ByteBuffer byteBuffer = image.getPlanes()[0].getBuffer();
byte[] data = new byte[byteBuffer.remaining()];
byteBuffer.get(data);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filePath));
fos.write(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
fos = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
image.close();
image = null;
}
}
}
}
複製代碼
相機會話狀態回調以前也說明過,在會話建立成功時,開始重複請求,以得到連續的預覽。post
CameraCaptureSession.StateCallback sessionsStateCallback = new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(CameraCaptureSession session) {
if (null == cameraDevice) {
return;
}
captureSession = session;
try {
captureSession.setRepeatingRequest(previewRequest, null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
Log.d(TAG, "相機訪問異常");
}
}
@Override
public void onConfigureFailed(CameraCaptureSession session) {
Log.d(TAG, "會話註冊失敗");
}
};
複製代碼
通過上述步驟,能夠在屏幕旋轉時也能保證正常的預覽窗口大小和預覽方向。ui
拍照按鈕的點擊事件監聽函數 takePhoto() 主要有三個步驟。
其中,屏幕顯示方向和拍照方向的對應關係用 PHOTO_ORTATION 定義。
private static final SparseIntArray PHOTO_ORITATION = new SparseIntArray();
static {
PHOTO_ORITATION.append(Surface.ROTATION_0, 90);
PHOTO_ORITATION.append(Surface.ROTATION_90, 0);
PHOTO_ORITATION.append(Surface.ROTATION_180, 270);
PHOTO_ORITATION.append(Surface.ROTATION_270, 180);
}
複製代碼
private void takePhoto() {
try {
photoRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
cameraOritation = PHOTO_ORITATION.get(displayRotation);
photoRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, cameraOritation);
photoRequestBuilder.addTarget(photoSurface);
photoRequest = photoRequestBuilder.build();
captureSession.stopRepeating();
captureSession.capture(photoRequest, sessionCaptureCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
Log.d(TAG, "相機訪問異常");
}
}
CameraCaptureSession.CaptureCallback sessionCaptureCallback = new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
try {
captureSession.setRepeatingRequest(previewRequest, null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
Log.d(TAG, "相機訪問異常");
}
}
};
複製代碼
整個流程並非多複雜,主要就是要注意手機屏幕旋轉時的預覽窗口、方向適配,以及拍照方向的矯正。
到目前爲止,相機預覽、拍照方面的流程和注意事項基本梳理完畢,後續梳理相機特性控制和錄像方面的知識。