我正在尝试在我的应用程序中使用相机,并希望能够在横向和纵向模式下使用它。我没有任何困难在横向模式下创建图片,但我还没有找到一个好的方法来保存纵向模式下的图片。
当我想在纵向模式下拍照时,我需要先将显示方向设置为纵向,如下所示:
switch (windowManager.getDefaultDisplay().getRotation()) {
case android.view.Surface.ROTATION_0:
mCamera.setDisplayOrientation(90);
break;
case android.view.Surface.ROTATION_90:
mCamera.setDisplayOrientation(0);
break;
case android.view.Surface.ROTATION_180:
mCamera.setDisplayOrientation(270);
break;
case android.view.Surface.ROTATION_270:
mCamera.setDisplayOrientation(180);
break;
}
但是照片仍然以横向模式保存。我找到的一个解决方案是像这样更改相机的旋转参数:
public void onOrientationChanged(int orientation) {
if (orientation == ORIENTATION_UNKNOWN) return;
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
orientation = (orientation + 45) / 90 * 90;
int rotation = 0;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - orientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + orientation) % 360;
}
mParameters.setRotation(rotation);
}
这种方法的问题在于可能只是在EXIF头中设置方向,而不实际旋转图片(这是我使用的设备的情况)。
另一种方法是在拍摄后旋转实际数据,像这样:
Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
bitmap= Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
currentData = stream.toByteArray();
但这种方法需要花费10秒钟的时间(太长了),虽然我可以将这段代码放入AsyncTask中,但我需要在一到几秒钟后获取数据,因此我仍然需要等待。
目前为止,我还没有找到更好的解决方案。
android.hardware.Camera
类和自定义SurfaceView来显示预览。 - Dennis van Opstal