Android 拍照 旋转
时间: 2023-11-11 18:58:47 浏览: 33
在 Android 中拍照时,由于摄像头的方向和设备方向可能不一致,导致拍出来的照片方向不正确。解决这个问题的方法是在拍照后对照片进行旋转。可以通过获取设备方向和摄像头方向的差值来计算需要旋转的角度,然后使用 Matrix 对图片进行旋转。
具体实现步骤如下:
1. 获取设备方向和摄像头方向的差值
```
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
```
2. 使用 Matrix 对图片进行旋转
```
Matrix matrix = new Matrix();
matrix.postRotate(result);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
```