How to set Android camera orientation properly? - android

I want to set the camera orientation according to the device orientation in Android but nothing seems to be working. I tried to rotate the Surface as well as the camera parameters but the camera preview in portrait mode always comes upside down. I would need to rotate it by 90 degree clockwise for it to be correct. Here is the code I am using right now which works in landscape mode only.
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
initCamera();
}
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.2;
double targetRatio = (double) w / h;
if (sizes == null)
return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
Log.d(TAG, "Checking size " + size.width + "w " + size.height
+ "h");
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the
// requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters parameters = camera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, width, height);
Log.d(TAG, "Surface size is " + width + "w " + height + "h");
Log.d(TAG, "Optimal size is " + optimalSize.width + "w " + optimalSize.height + "h");
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
// parameters.setPreviewSize(width, height);
camera.setParameters(parameters);
camera.startPreview();
}
};

From other member and my problem:
Camera Rotation issue depend on different Devices and certain Version.
Version 1.6: to fix the Rotation Issue, and it is good for most of devices
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
p.set("orientation", "portrait");
p.set("rotation",90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
p.set("orientation", "landscape");
p.set("rotation", 90);
}
Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
Version 2.2: not for all devices
camera.setDisplayOrientation(90);
http://code.google.com/p/android/issues/detail?id=1193#c42

From the Javadocs for setDisplayOrientation(int) (Requires API level 9):
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);
}

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:
Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.
The method:
protected void setDisplayOrientation(Camera camera, int angle){
Method downPolymorphic;
try
{
downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (downPolymorphic != null)
downPolymorphic.invoke(camera, new Object[] { angle });
}
catch (Exception e1)
{
}
}
And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :
if (Integer.parseInt(Build.VERSION.SDK) >= 8)
setDisplayOrientation(mCamera, 90);
else
{
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
p.set("orientation", "portrait");
p.set("rotation", 90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
p.set("orientation", "landscape");
p.set("rotation", 90);
}
}

I faced the issue when i was using ZBar for scanning in tabs.
Camera orientation issue. Using below code i was able to resolve issue.
This is not the whole code snippet, Please take only help from this.
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (isPreviewRunning) {
mCamera.stopPreview();
}
setCameraDisplayOrientation(mCamera);
previewCamera();
}
public void previewCamera() {
try {
// Hard code camera surface rotation 90 degs to match Activity view
// in portrait
mCamera.setPreviewDisplay(mHolder);
mCamera.setPreviewCallback(previewCallback);
mCamera.startPreview();
mCamera.autoFocus(autoFocusCallback);
isPreviewRunning = true;
} catch (Exception e) {
Log.d("DBG", "Error starting camera preview: " + e.getMessage());
}
}
public void setCameraDisplayOrientation(android.hardware.Camera camera) {
Camera.Parameters parameters = camera.getParameters();
android.hardware.Camera.CameraInfo camInfo =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(getBackFacingCameraId(), camInfo);
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.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 (camInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (camInfo.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (camInfo.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
private int getBackFacingCameraId() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}

I finally fixed this using the Google's camera app. It gets the phone's orientation by using a sensor and then sets the EXIF tag appropriately. The JPEG which comes out of the camera is not oriented automatically.
Also, the camera preview works properly only in the landscape mode. If you need your activity layout to be oriented in portrait, you will have to do it manually using the value from the orientation sensor.

This problem was solved a long time ago but I encountered some difficulties to put all pieces together so here is my final solution, I hope this will help others :
public void startPreview() {
try {
Log.i(TAG, "starting preview: " + started);
// ....
Camera.CameraInfo camInfo = new Camera.CameraInfo();
Camera.getCameraInfo(cameraIndex, camInfo);
int cameraRotationOffset = camInfo.orientation;
// ...
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
Camera.Size previewSize = null;
float closestRatio = Float.MAX_VALUE;
int targetPreviewWidth = isLandscape() ? getWidth() : getHeight();
int targetPreviewHeight = isLandscape() ? getHeight() : getWidth();
float targetRatio = targetPreviewWidth / (float) targetPreviewHeight;
Log.v(TAG, "target size: " + targetPreviewWidth + " / " + targetPreviewHeight + " ratio:" + targetRatio);
for (Camera.Size candidateSize : previewSizes) {
float whRatio = candidateSize.width / (float) candidateSize.height;
if (previewSize == null || Math.abs(targetRatio - whRatio) < Math.abs(targetRatio - closestRatio)) {
closestRatio = whRatio;
previewSize = candidateSize;
}
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break; // Natural orientation
case Surface.ROTATION_90:
degrees = 90;
break; // Landscape left
case Surface.ROTATION_180:
degrees = 180;
break;// Upside down
case Surface.ROTATION_270:
degrees = 270;
break;// Landscape right
}
int displayRotation;
if (isFrontFacingCam) {
displayRotation = (cameraRotationOffset + degrees) % 360;
displayRotation = (360 - displayRotation) % 360; // compensate
// the
// mirror
} else { // back-facing
displayRotation = (cameraRotationOffset - degrees + 360) % 360;
}
Log.v(TAG, "rotation cam / phone = displayRotation: " + cameraRotationOffset + " / " + degrees + " = "
+ displayRotation);
this.camera.setDisplayOrientation(displayRotation);
int rotate;
if (isFrontFacingCam) {
rotate = (360 + cameraRotationOffset + degrees) % 360;
} else {
rotate = (360 + cameraRotationOffset - degrees) % 360;
}
Log.v(TAG, "screenshot rotation: " + cameraRotationOffset + " / " + degrees + " = " + rotate);
Log.v(TAG, "preview size: " + previewSize.width + " / " + previewSize.height);
parameters.setPreviewSize(previewSize.width, previewSize.height);
parameters.setRotation(rotate);
camera.setParameters(parameters);
camera.setPreviewDisplay(mHolder);
camera.startPreview();
Log.d(TAG, "preview started");
started = true;
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}

check out this solution
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);
}

Related

Rotating Camera causes shrinking of Surface View

I have implemented a custom camera in my android app but when I rotate my device my surface view is rotated but the issue is it shrinks and I want same ratio image from both the orientation.
In my portrait view, my Preview is shrinking but I got the full-size image for example when I take the image from landscape view I am getting the image of size 1080*960 where 1080 is width and 960 is height as well when I clicked the image from portrait view height of image is 1080 and width is 960 but I want image as same as landscape mode
Below is my Surface code
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
if (mCamera != null) {
stopCameraPreview();
mCamera.release();
}
getCamera(mCameraID);
setCameraDisplayOrientation(activity,mCameraID,mCamera);
startCameraPreview();
}
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);
}
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) h / w;
if (sizes == null)
return null;
Camera.Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
for (Camera.Size size : sizes) {
double ratio = (double) size.height / size.width;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Camera.Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
try {
mCamera.startPreview();
mIsSafeToTakePhoto = true;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// The surface is destroyed with the visibility of the SurfaceView is set to View.Invisible
try {
if (mCamera != null) {
stopCameraPreview();
mCamera.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}

Camera2 front camera preview rotation

i am working on camera2 and have got a problem with rotation.
In some devices, when switching to front camera, preview is being rotated 180 degrees.
Was looking such a "setDefaultOrientation()" method for camera2 but couldn't find it.
Thanks
With a GLSurfaceView, you're presumably using a SurfaceTexture to map the camera preview stream into a GL texture, and then rendering it.
The image data in the texture is not automatically rotated to be 'upright' - for one, there's no way for the OS to know how you're going to render your texture.
However, the SurfaceTexture has a getTransformMatrix call, which when connected to the camera2 API, will give you the necessary transform from the camera's orientation to the device's native orientation (typically portrait for phones, landscape for tablets, but not always). You'll then have to add the transform from the native orientation to your app's orientation to this matrix, and then apply the combined matrix transform to adjust the preview image.
you can set the correct image rotation in CaptureRequest object while capturing an image in CameraCaptureSession.StateCallback using CameraCharacterisitics
CameraCharacterisitics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
like this.
private CameraCaptureSession.StateCallback sessionStateCallback = new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
captureSession = session;
try {
CaptureRequest.Builder builder = session.getDevice().createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
builder.addTarget(imageReader.getSurface());
builder.set(CaptureRequest.JPEG_ORIENTATION, cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION));
session.capture(builder.build(), null, backgroundHandler);
} catch (CameraAccessException e) {
Log.d("tag", e.getMessage());
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession session) {
}
};
you can try this code for open your camera
I hope this will help
public void startPreview() {
try {
Log.i(TAG, "starting preview: " + started);
// ....
Camera.CameraInfo camInfo = new Camera.CameraInfo();
Camera.getCameraInfo(cameraIndex, camInfo);
int cameraRotationOffset = camInfo.orientation;
// ...
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
Camera.Size previewSize = null;
float closestRatio = Float.MAX_VALUE;
int targetPreviewWidth = isLandscape() ? getWidth() : getHeight();
int targetPreviewHeight = isLandscape() ? getHeight() : getWidth();
float targetRatio = targetPreviewWidth / (float) targetPreviewHeight;
Log.v(TAG, "target size: " + targetPreviewWidth + " / " + targetPreviewHeight + " ratio:" + targetRatio);
for (Camera.Size candidateSize : previewSizes) {
float whRatio = candidateSize.width / (float) candidateSize.height;
if (previewSize == null || Math.abs(targetRatio - whRatio) < Math.abs(targetRatio - closestRatio)) {
closestRatio = whRatio;
previewSize = candidateSize;
}
}
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break; // Natural orientation
case Surface.ROTATION_90:
degrees = 90;
break; // Landscape left
case Surface.ROTATION_180:
degrees = 180;
break;// Upside down
case Surface.ROTATION_270:
degrees = 270;
break;// Landscape right
}
int displayRotation;
if (isFrontFacingCam) {
displayRotation = (cameraRotationOffset + degrees) % 360;
displayRotation = (360 - displayRotation) % 360; // compensate
// the
// mirror
} else { // back-facing
displayRotation = (cameraRotationOffset - degrees + 360) % 360;
}
Log.v(TAG, "rotation cam / phone = displayRotation: " + cameraRotationOffset + " / " + degrees + " = "
+ displayRotation);
this.camera.setDisplayOrientation(displayRotation);
int rotate;
if (isFrontFacingCam) {
rotate = (360 + cameraRotationOffset + degrees) % 360;
} else {
rotate = (360 + cameraRotationOffset - degrees) % 360;
}
Log.v(TAG, "screenshot rotation: " + cameraRotationOffset + " / " + degrees + " = " + rotate);
Log.v(TAG, "preview size: " + previewSize.width + " / " + previewSize.height);
parameters.setPreviewSize(previewSize.width, previewSize.height);
parameters.setRotation(rotate);
camera.setParameters(parameters);
camera.setPreviewDisplay(mHolder);
camera.startPreview();
Log.d(TAG, "preview started");
started = true;
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}

Camera records upside down sometimes

When i am in landscape, if it's at 0degrees, it captures a good video, but if i turn the phone over 180 degrees, it will record upside down, how can i change this?
When i start recording i do this code:
myMediaRecorder.setPreviewDisplay(mySurfaceHolder.getSurface());
if (rotationInDegreeValue == 90) {
LogService.log(TAG, "set orientation hint : " + 0);
myMediaRecorder.setOrientationHint(0);
} else if (rotationInDegreeValue == 270) {
LogService.log(TAG, "set orientation hint : " + 180);// 180
myMediaRecorder.setOrientationHint(180);
}
myMediaRecorder.prepare();
myMediaRecorder.start();
Then, i have an orientation listener:
orientationListener = new OrientationEventListener(getActivity(), SensorManager.SENSOR_DELAY_UI) {
#Override
public void onOrientationChanged(int orientation) {
LogService.log(TAG, "onOrientationChanged");
if ((myCamera == null)) {
return;
}
Log.d(TAG, "orientation changed : " + orientation);
if (((orientation < 45) || (orientation > 315) || ((orientation < 225) && (orientation > 135))) && !isRecording) {
if (!isAlertShown && !isUserListDisplayed) {
// AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
// alertDialogBuilder.setTitle("Orientation").setMessage("Return to landscape").setCancelable(false);
// orientationAlert = alertDialogBuilder.create();
// orientationAlert.show();
isAlertShown = true;
}
} else {
if (isAlertShown) {
// orientationAlert.hide();
// orientationAlert.dismiss();
isAlertShown = false;
}
}
rotateCamera();
}
};
This is the RotateCamera Function:
private void rotateCamera() {
LogService.log(TAG, "rotateCamera()");
int cameraId = CameraInfo.CAMERA_FACING_BACK;
if (isUsingBackCam) {
cameraId = CameraInfo.CAMERA_FACING_FRONT;
}
android.hardware.Camera.CameraInfo myCameraInfo = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, myCameraInfo);
Display display;
display = getActivity().getWindow().getWindowManager().getDefaultDisplay();
int rotation = display.getRotation();
int degrees = 0;
Point size = new Point();
display.getSize(size);
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
rotationInDegreeValue = 0;
SCREEN_HEIGHT = size.x;
break;
case Surface.ROTATION_90:
degrees = 90;
rotationInDegreeValue = 90;
SCREEN_HEIGHT = size.y;
break;
case Surface.ROTATION_180:
degrees = 180;
rotationInDegreeValue = 180;
break;
case Surface.ROTATION_270:
rotationInDegreeValue = 270;
degrees = 270;
SCREEN_HEIGHT = size.y;
break;
}
int result;
if (myCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (myCameraInfo.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = ((myCameraInfo.orientation - degrees) + 360) % 360;
}
if (!isRecording) {
try {
myCamera.setDisplayOrientation(result);
} catch (Exception e) {
LogService.err(TAG, e.getMessage(), e, 1);
}
}
}
What do i have to do, to stop the camera from recording upside down, when i turn the phone 180 degrees. I tried to comment out the orientation listener, but still no luck.
Also, i do not know if it is important of not, but this happens in a fragment. The Activity of the fragment, does not have onconfigurationchanged set.
The setOrientationHint function worked, but i had to append more videos, and when this was happening, the composition matrix of the videos was getting lost.
I have changed in the manifest, from SensorLandscape to Landscape, and this is how i solved this issue.

Rotating a Camera SurfaceView to portrait

I have looked up a few posts on changing the orientation of the camera with a surface view, but I have taken my code from the examples at:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html
The function that provides the dimensions looks like this...
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for (Size size : sizes) {
double ratio = (double) size.width / size.height;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if (optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
My problem is that when I change the orientation of the device, the preview picture stays landscape. I tried setting the orientation of the camera but this resulted in very strange results. Does anyone know what I need to change to have this rotate properly?
The code to correctly adjust the camera preview orientation is a bit complex, since it has to take into account
The relative orientation of the sensor and the device's 'natural' orientation (which is portrait for phones, landscape for tablets, typically)
The current UI orientation of the device (portrait, landscape or the reverse of each)
Whether the camera in question is the front or the back camera (since the front preview stream is mirrored horizontally)
The documentation for Camera.setDisplayOrientation has sample code on how to deal with this correctly. I'm reproducing it here:
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);
}
Call this after your UI has been drawn (onSurfaceChanged would work as an indicator) or the device UI rotates (onConfigurationChanged would work as an indicator).
I was able to solve the rotation problem by putting the following code in onSurfaceChanged():
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
mCamera.setDisplayOrientation(90);
} else {
mCamera.setDisplayOrientation(0);
}
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
BUT this created another problem, or better put, didn't solve a problem-while oriented correctly, the preview image still only took up the same amount of space that the landscape view did. I ended up just giving up and forcing landscape orientation with:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
in onCreate() and designed my layout for landscape. Best of luck, and I hope someone has an answer for this secondary problem!
Try this out, but I tried in Samsung Galaxy Tab
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where to draw.
mCamera = Camera.open();
Parameters params = mCamera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
{
params.set("orientation", "portrait");
mCamera.setDisplayOrientation(90);
}
try
{
mCamera.setPreviewDisplay(holder);
}
catch (IOException exception)
{
mCamera.release();
mCamera = null;
}
}
I solved this issue by adding:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
To the onCreate event.
Please try this..
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height)
{
// TODO Auto-generated method stub
if(previewing)
{
camera.stopPreview();
previewing = false;
}
Camera.Parameters parameters = camera.getParameters();
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int or=cameraInfo.orientation;
// You need to choose the most appropriate previewSize for your app
// .... select one of previewSizes here
/* parameters.setPreviewSize(previewSize.width, previewSize.height);*/
if(display.getRotation() == Surface.ROTATION_0)
{
camera.setDisplayOrientation(90);
or=90;
}
if(display.getRotation() == Surface.ROTATION_180)
{
camera.setDisplayOrientation(270);
or=270;
}
if(display.getRotation() == Surface.ROTATION_270)
{
camera.setDisplayOrientation(180);
or=180;
}
parameters.setRotation(or);
camera.setParameters(parameters);
try
{
camera.setPreviewDisplay(cameraSurfaceHolder);
camera.startPreview();
previewing = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well i Do this!
I have solved this issue in in this way in surfaceCreated() method
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
} catch (RuntimeException e) {
System.err.println(e);
return;
}
Camera.Parameters param;
param = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE)
{
param.set("orientation", "portrait");
setCameraDisplayOrientation(this,1,camera);
}
camera.setParameters(param);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
System.err.println(e);
return;
}
}
add this method below
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);
}
3: Make sure you have added camera permiison to support for nougat in a activity before this activity calling dont call permission for camera in this activity because surfacecreated call as the activity created, and your permission will be pending to open camera
Only add this
mCamera.setDisplayOrientation(90);

Android camera rotate

I have a Motorola Defy OS Android 2.1 and I make an application with camera Preview. The problem is that the camera works fine on Samsung Galaxy S with Android 2.1, but on Motorola the camera is rotated with 90 degrees. I have tried to do this:
Parameters parameters = camera.getParameters();
parameters.setRotation(90);
but it's not working. I didn't find any solution yet.
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
camera.setDisplayOrientation(90);
lp.height = previewSurfaceHeight;
lp.width = (int) (previewSurfaceHeight / aspect);
} else {
camera.setDisplayOrientation(0);
lp.width = previewSurfaceWidth;
lp.height = (int) (previewSurfaceWidth / aspect);
}
There is official example code for this in the Android docs now (under setDisplayOrientation()):
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);
}
camera.setDisplayOrientation(int) is not exist under 2.1!
And this code may work, but fail in my milestone/droid :(
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
you can see more in http://code.google.com/p/android/issues/detail?id=1193#c42
I found this code that works in Android 1.6 and over (works for me using 2.1 and present preview in portrait mode without rotating)
public void surfaceCreated(SurfaceHolder holder){
try{
camera = Camera.open();
setDisplayOrientation(camera, 90);
camera.setPreviewDisplay(holder);
camera.startPreview();
}catch(IOException e){
Log.d("CAMERA", e.getMessage());
}
}
protected void setDisplayOrientation(Camera camera, int angle){
Method downPolymorphic;
try
{
downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (downPolymorphic != null)
downPolymorphic.invoke(camera, new Object[] { angle });
}
catch (Exception e1)
{
}
}
The activity has android:screenOrientation="portrait" on AndroidManifest.xml
http://code.google.com/p/android/issues/detail?id=1193#c42
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);
}
I think that you can not make any setting to support the API 2.2 to 2.1. The API doesn't have in your current device lib. You must change to 2.2 to support API level 8. By the way, I also try to use the API level 7:
Parameters parameters = camera.getParameters();
parameters.setRotation(90);
This function works well on the Samsung Galaxy Tab but Nexus one. The Samsung Galaxy Tab uses OS 2.2.0 and the Nexus one uses OS 2.2.1. When I try to use API level 8:
camera.setDisplayOrientation(90);
both of them work well. So I think that the API level 7 has problem when we use on Android OS 2.2.1.

Categories

Resources