Android平台如何打开“前置摄像头”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2779002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:19:12  来源:igfitidea点击:

How do I open the "front camera" on the Android platform?

androidcameraandroid-camera

提问by Sol

More generally, if a device has more than one embedded camera, is there a way to initialize one of them in particular?

更一般地说,如果一个设备有多个嵌入式摄像头,有没有办法特别初始化其中一个摄像头?

I didn't find it in Android reference documentation:

我在 Android 参考文档中没有找到它:

Samsung SHW-M100S has two cameras. If there is no reference to use two cameras, any idea how Samsung did...?

三星 SHW-M100S 有两个摄像头。如果没有提到使用两个摄像头,你知道三星是怎么做的吗......?

回答by

private Camera openFrontFacingCameraGingerbread() {
    int cameraCount = 0;
    Camera cam = null;
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    cameraCount = Camera.getNumberOfCameras();
    for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
        Camera.getCameraInfo(camIdx, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                cam = Camera.open(camIdx);
            } catch (RuntimeException e) {
                Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;
}

Add the following permissions in the AndroidManifest.xmlfile:

AndroidManifest.xml文件中添加以下权限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />

Note:This feature is available in Gingerbread(2.3) and Up Android Version.

注意:此功能在 Gingerbread(2.3) 和 Up Android 版本中可用。

回答by iantonuk

All older answers' methods are deprecated by Google (supposedly because of troubles like this), since API 21 you need to usethe Camera 2 API:

所有旧答案的方法都被谷歌弃用(据说是因为这样的麻烦),因为 API 21 你需要使用Camera 2 API:

This class was deprecated in API level 21. We recommend using the new android.hardware.camera2 API for new applications.

此类在 API 级别 21 中已弃用。我们建议对新应用程序使用新的 android.hardware.camera2 API。

In the newer APIyou have almost complete powerover the Android device camera and documentation explicitly advice to

较新的 API 中,几乎可以完全控制Android 设备相机和文档,明确建议

String[] getCameraIdList()

and then use obtained CameraId to open the camera:

然后使用获得的CameraId打开相机:

void openCamera(String cameraId, CameraDevice.StateCallback callback, Handler handler)

99% of the frontal cameras have id = "1", and the back camera id = "0"according to this:

99% 的前置摄像头的 id = "1",后置摄像头 id = "0"据此:

Non-removable cameras use integers starting at 0 for their identifiers, while removable cameras have a unique identifier for each individual device, even if they are the same model.

不可移动相机使用从 0 开始的整数作为标识符,而可移动相机对每个单独的设备都有唯一的标识符,即使它们是相同的型号。

However, this means if device situation is rare like just 1-frontal -camera tablet you need to count how many embeddedcameras you have, and place the order of the camera by its importance ("0"). So CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0, which implies that the back camera is more importantthan frontal.

但是,这意味着如果设备情况很少见,例如只有 1 个前置摄像头平板电脑,您需要计算您拥有多少个嵌入式摄像头,并根据摄像头的重要性(“0”)排列摄像头的顺序。所以CAMERA_FACING_FRONT == 1 CAMERA_FACING_BACK == 0,这意味着后置摄像头比正面更重要

I don't know about a uniformmethod to identify the frontal camera on all Android devices. Simply said, the Android OS inside the device can't really find out which camera is exactly where for some reasons: maybe the only camera hardcoded id is an integer representing its importance or maybe on some devices whichever side you turn will be .. "back".

我不知道在所有 Android 设备上识别前置摄像头的统一方法。简单地说,由于某些原因,设备内部的 Android 操作系统无法真正找出哪个摄像头的确切位置:也许唯一硬编码的摄像头 id 是一个表示其重要性的整数,或者在某些设备上,无论您转向哪一侧都会是……”背部”。

Documentation: https://developer.android.com/reference/android/hardware/camera2/package-summary.html

文档https: //developer.android.com/reference/android/hardware/camera2/package-summary.html

Explicit Examples: https://github.com/googlesamples/android-Camera2Basic

显式示例https: //github.com/googlesamples/android-Camera2Basic



For the older API(it is not recommended, because it will not work on modern phones newer Android version and transfer is a pain-in-the-arse). Just use the same IntegerCameraID (1) to open frontal camera like in this answer:

对于较旧的 API(不推荐,因为它不适用于现代手机较新的 Android 版本,并且传输是一种麻烦)。只需使用相同的IntegerCameraID (1) 打开前置摄像头,就像在这个答案中一样

cam = Camera.open(1);


If you trust OpenCVto do the camera part:

如果您信任OpenCV来完成相机部分:

Inside

里面

    <org.opencv.android.JavaCameraView
    ../>

use the following for the frontal camera:

对前置摄像头使用以下内容:

        opencv:camera_id="1"

回答by CommonsWare

As of Android 2.1, Android only supports a single camera in its SDK. It is likely that this will be added in a future Android release.

从 Android 2.1 开始,Android 仅支持其 SDK 中的单个摄像头。这很可能会在未来的 Android 版本中添加。

回答by Mahesh

public void surfaceCreated(SurfaceHolder holder) {
    try {
        mCamera = Camera.open();
        mCamera.setDisplayOrientation(90);
        mCamera.setPreviewDisplay(holder);

        Camera.Parameters p = mCamera.getParameters();
        p.set("camera-id",2);
        mCamera.setParameters(p);   
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

回答by Airsource Ltd

For API 21 (5.0) and later you can use the CameraManager API's

对于 API 21 (5.0) 及更高版本,您可以使用CameraManager API

try {
    String desiredCameraId = null;
    for(String cameraId : mCameraIDsList) {
        CameraCharacteristics chars =  mCameraManager.getCameraCharacteristics(cameraId);
        List<CameraCharacteristics.Key<?>> keys = chars.getKeys();
        try {
            if(CameraCharacteristics.LENS_FACING_FRONT == chars.get(CameraCharacteristics.LENS_FACING)) {
               // This is the one we want.
               desiredCameraId = cameraId;
               break;
            }
        } catch(IllegalArgumentException e) {
            // This key not implemented, which is a bit of a pain. Either guess - assume the first one
            // is rear, second one is front, or give up.
        }
    }
}

回答by Shubham Raitka

To open the backcamera:-

要打开后置摄像头:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

To open the frontcamera:-

要打开前置摄像头:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
when {
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT)  // Tested on API 24 Android version 7.0(Samsung S6)
     }
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 27 Android version 8.0(Nexus 6P)
         cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
     }
     else -> cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1)  // Tested API 21 Android version 5.0.1(Samsung S4)
}
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

I could not make it work for API 28 and above. Also, opening the front camera directly is not possible in some devices(depends on the manufacturer).

我无法使其适用于 API 28 及更高版本。此外,某些设备无法直接打开前置摄像头(取决于制造商)。

回答by Wesley Wiser

With the release of Android 2.3(Gingerbread), you can now use the android.hardware.Cameraclass to get the number of cameras, information about a specific camera, and get a reference to a specific Camera. Check out the new CameraAPIs here.

随着Android 2.3(Gingerbread) 的发布,您现在可以使用android.hardware.Camera该类来获取摄像头数量、特定摄像头的信息以及获取特定Camera. 在此处查看新CameraAPI 。

回答by Dheerendra Mitm

build.gradle

构建.gradle

 dependencies {
       compile 'com.google.android.gms:play-services-vision:9.4.0+'
    }

Set View

设置视图

CameraSourcePreview mPreview = (CameraSourcePreview) findViewById(R.id.preview);

GraphicOverlay mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);

CameraSource mCameraSource = new CameraSource.Builder(context, detector)
                            .setRequestedPreviewSize(640, 480)
                            .setFacing(CameraSource.CAMERA_FACING_FRONT)
                            .setRequestedFps(30.0f)
                            .build();

           mPreview.start(mCameraSource, mGraphicOverlay);

回答by Amalan Dhananjayan

Camera camera;   
if (Camera.getNumberOfCameras() >= 2) {

    //if you want to open front facing camera use this line   
    camera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);

    //if you want to use the back facing camera
    camera = Camera.open(CameraInfo.CAMERA_FACING_BACK);                
}

try {
    camera.setPreviewDisplay("your surface holder here");
    camera.startPreview();      
} catch (Exception e) {  
    camera.release();
}

/* This is not the proper way, this is a solution for older devices that run Android 4.0 or older. This can be used for testing purposes, but not recommended for main development. This solution can be considered as a temporary solution only. But this solution has helped many so I don't intend to delete this answer*/

/* 这不是正确的方法,这是针对运行 Android 4.0 或更早版本的旧设备的解决方案。这可用于测试目的,但不建议用于主要开发。此解决方案只能视为临时解决方案。但是这个解决方案帮助了很多,所以我不打算删除这个答案*/