【问题标题】:Android camera rotation for portrait mode picturesAndroid相机旋转肖像模式图片
【发布时间】:2014-04-19 06:17:41
【问题描述】:

我正在尝试制作自定义相机应用。我在没有预览的情况下从前置摄像头拍照,但生成的图像会根据前置摄像头方向旋转。

我在堆栈中搜索了很多帖子,也是在 android 文档中描述的here。

这是我想出的解决方案:

    private void prepareCamera(Activity a){
    //Rotation
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_FRONT,info);

    int rotation = a.getWindowManager().getDefaultDisplay().getRotation();
    int degrees = 0;

    Log.d("TEST","rotation: "+rotation);

    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
    }

    Log.d("TEST","degrees: "+degrees);

    int result = (info.orientation + degrees) % 360;
    Log.d("TEST","result: "+result);
    result = (360 - result) % 360; //Compensate the mirror

    Log.d("TEST","result: "+result);

    //camera.setDisplayOrientation(result);

    //Parameters
    Camera.Parameters params = camera.getParameters();
    params.setRotation(result);
    params.setJpegQuality(100);

    camera.setParameters(params);

    //Preview
    SurfaceView view = new SurfaceView(context);

    try{
        camera.setPreviewDisplay(view.getHolder());
    }catch(IOException e){
        throw new RuntimeException(e);
    }

    camera.startPreview();
}

它有效,但我有两个问题

1) 我有一条线,我从 android 文档中获取的,“补偿镜像”。如果我不删除那条线,图片会根据相机方向很好地旋转,但它们会被 180º 超越。如果我删除它,图片就很好。我想了解原因,如果有人可以解释一下。

我认为这是因为我从文档中获取的示例代码是为 SurfaceView 制作的,它调用 setDisplayOrientation(result);,当我在 .setRotation(result); 中使用结果时。或许与此有关?

2) 当我在测试时,我可以将手机旋转到各个方向,但要倒置并很好地旋转图片。但是当我将手机倒置时,它们旋转了 90 度,但倒置了。因为它们像自然方向一样被处理。也许android不会跟踪颠倒旋转?如果是这样,他们为什么要在他们提供的示例中使用案例。

【问题讨论】:

    标签: android android-camera


    【解决方案1】:

    请看setRotation() sample:

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

    Display.getRotation() 与方向传感器不同,仅限于您当前 Activity 支持的方向。在某些设备上,系统不支持纵向倒置方向。

    【讨论】:

    • 谢谢,我明白了。关于我的第一个问题?你知道会发生什么吗?
    猜你喜欢
    • 2014-03-13
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    相关资源
    最近更新 更多