我正在使用最低API级别16的Android应用程序工作。我必须为实时帧构建自定义的Camera Builder,并为OCR处理它们。我已经设置了表面视图并添加了预览回调,以便可以实时运行框架上 onPreviewFrame(byte [] bytes,Camera camera)方法。
默认情况下,屏幕处于横向模式,并且在大多数设备中我都获得正确的方向。 但是在某些设备中,这种方法使图像旋转了180度,但无法处理。
Display display = ((WindowManager) Objects.requireNonNull(context.getSystemService(WINDOW_SERVICE))).getDefaultDisplay();
return display.getRotation();
以上方法在两个设备中均返回90度旋转。但是一方面,图像具有正确的方向,另一方面,图像旋转了180度。这是相机类:
public abstract class Camera {
private static android.hardware.Camera mCamera;
/**
* A safe way to get an instance of the Camera object.
*/
private static android.hardware.Camera getCameraInstance(int cameraFacing) {
android.hardware.Camera c = null;
try {
c = android.hardware.Camera.open(cameraFacing); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public static void closeCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
public static void autoFocus() {
if (mCamera != null)
try {
mCamera.autoFocus(null);
} catch (Exception ignored) {
}
}
/**
* focusMode: android.hardware.Camera.Parameters
* cameraFacing: android.hardware.Camera.CameraInfo.FACING_FRONT or FACING_BACK
*/
public static class CameraBuilder {
private static final String TAG = CameraBuilder.class.getSimpleName();
private String focusMode = android.hardware.Camera.Parameters.FOCUS_MODE_AUTO;
private int cameraFacing = android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK;
private int displayOrientation = 0;
public CameraBuilder() {
}
/**
* @param focusMode default: android.hardware.Camera.Parameters.FOCUS_MODE_AUTO
* @return CameraBuilder
*/
public CameraBuilder setFocusMode(String focusMode) {
this.focusMode = focusMode;
return this;
}
/**
* @param cameraFacing default : android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK
* @return CameraBuilder
*/
public CameraBuilder setCameraFacing(int cameraFacing) {
this.cameraFacing = cameraFacing;
return this;
}
public CameraBuilder setDisplayOrientation(int orientation) {
this.displayOrientation = orientation;
return this;
}
public android.hardware.Camera build() {
try {
mCamera = getCameraInstance(cameraFacing);
android.hardware.Camera.Parameters params = mCamera.getParameters();
params.setFocusMode(focusMode);
mCamera.setParameters(params);
} catch (Exception e) {
// Camera is not available (in use or does not exist)
Log.e(TAG, "Camera Exception: " + e.getMessage());
}
mCamera.setDisplayOrientation(displayOrientation);
return mCamera;
}
}
}
这是我的相机的初始化。
camera = new CameraBuilder()
.setCameraFacing(Camera.CameraInfo.CAMERA_FACING_BACK)
.setFocusMode(android.hardware.Camera.Parameters.FOCUS_MODE_AUTO)
.setDisplayOrientation(0)
.build();