Camera orientation in webcam and phone

2019-08-30 12:54发布

问题:

i have done an application where i have to record video.when i run it in my emulator using web cam camera orientation is alright,but when i run the same in phone the orientation gets 90 degree changed.cant understand y its happening can any one help me ? here is my code---

private boolean prepareMediaRecorder(){
    myCamera = getCameraInstance();         
    mediaRecorder = new MediaRecorder();
    myCamera.unlock();
    mediaRecorder.setCamera(myCamera);

    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

    mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

    mediaRecorder.setOutputFile("/sdcard/video.mp4");

    mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
    mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M

    mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

    try {
        mediaRecorder.prepare();
    } catch (IllegalStateException e) {
        releaseMediaRecorder();
        return false;
    } catch (IOException e) {
        releaseMediaRecorder();
        return false;
    }
    return true;

}

回答1:

Preview orientation depends on the orientation of the device and camera orientation.

Basically what you need is to calculate the orientation of the camera preview based on those conditions.

We need two help methods:

1 - Calculate the device orientation:

public int getDeviceOrientation(Context context) {

    int degrees = 0;
    WindowManager windowManager =
            (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    int rotation = windowManager.getDefaultDisplay().getRotation();

    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;
    }

    return degrees;
}  

2 - Calculate Camera preview rotation:

public static int getPreviewOrientation(Context context, int cameraId) {

   int temp = 0;
   int previewOrientation = 0;

   Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
   Camera.getCameraInfo(cameraId, cameraInfo);

   int deviceOrientation = getDeviceOrientation(context);
   temp = cameraInfo.orientation - deviceOrientation + 360;
   previewOrientation = temp % 360;

    return previewOrientation;
}

At your code, before mediaRecorder.prepare();

int rotation = getPreviewOrientation(context, cameraId);
mediaRecorder.setOrientationHint(rotation);  

To use those methods is required a context and the camera Id in use.