问题出现的原因是不同设备的相机硬件与软件设置不同,导致拍摄的照片旋转角度不同。可以通过以下方式解决:
在拍摄照片时,可以通过监听 CameraCaptureSession 的 onCaptureCompleted 回调方法获取到当前照片的方向信息:
private CameraCaptureSession.CaptureCallback mCaptureCallback =
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session,
@NonNull CaptureRequest request,
@NonNull TotalCaptureResult result) {
int orientation = result.get(CaptureResult.JPEG_ORIENTATION);
// do something with the orientation
}
};
根据获取到的照片方向信息,可以通过 Matrix 类对图片进行旋转。例如:
public static Bitmap rotateBitmap(Bitmap source, int orientation) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, true);
}
其中,orientation 参数为照片的方向信息。
最后,将旋转后的照片展示出来即可。
Bitmap bitmap = rotateBitmap(originalBitmap, orientation);
imageView.setImageBitmap(bitmap);
这样就可以解决 Android Camera2 在某些设备上拍摄的照片旋转了90度的问题了。