我正在尝试在我的应用程序中使用相机,并且我希望能够在横向和纵向模式下使用它。我在横向模式下创建图片没有困难,但我还没有找到在纵向模式下保存图片的好方法。
当我想在纵向模式下拍照时,我需要先将 displayorientation 设置为纵向,如下所示:
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 header 中设置方向,而不是实际旋转图片(我正在使用的设备就是这种情况)。
另一种方法是在拍照后旋转实际数据,如下所示:
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 中,但我需要一到几秒后的数据,所以我仍然需要等待。
到目前为止我还没有找到更好的解决方案。
最佳答案
我找到了一个解决方案,它让我仍然需要等待一两秒钟,但这对我来说已经足够快了。 这是一个非常简单的修复,只需使用 Matrix.postRotate 方法,但要更改:
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
到:
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
对我来说,这是一个非常好的解决方案,尤其是因为我已经在其他地方使用了 .jpg 图像,所以无论如何将 Bitmap 压缩为 .png 没有多大意义。
关于java - Android 相机在人像模式下保存图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37135675/