I am developing an android application which uses camera preview in the background. It is working fine across different devices.
But when tested on Nexus 5X, the camera preview is upside down. I am using these permission in manifest
<uses-permission android:name="android.permission.CAMERA" />
My camera code is as follows
public void startCamera(int myTexture)
{
surface = new SurfaceTexture(myTexture);
try {
camera = Camera.open();
} catch (Exception e) {
Log.e("MainActivity", "failed to open Camera");
e.printStackTrace();
}
try
{
camera1.setPreviewTexture(surface);
camera1.startPreview();
}
catch (IOException ioe)
{
Log.w("MainActivity","Camera launch failed");
}
}
Tried camera.setDisplayOrientation(180); But didn't work. Please Help!
As explained in this pro-tip, you need to use setDisplayOrientation() to properly rotate the preview to match the device orientation.
The full code from the documentation (which works on the Nexus 5X) is:
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.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;
}
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;
}
camera.setDisplayOrientation(result);
}
Since you are using a SurfaceTexture you will have to handle the rotation yourself. As stated in the documentation the method does not affect the order of the bytes:
This does not affect the order of byte array passed in onPreviewFrame(byte[], Camera), JPEG pictures, or recorded videos.
That said you can manually rotate the bytes directly on the GPU performing the action on the OpenGL Texture. Note that rotation of 180° is equivalent to flip bytes once vertically and once horizontally, which on OpenGL means that can either:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With