1. 程式人生 > >android Camera 如何判斷當前使用的攝像頭是前置還是後置

android Camera 如何判斷當前使用的攝像頭是前置還是後置

轉載自:http://blog.csdn.net/fulinwsuafcie/article/details/8862836

現在 Android 平臺的智慧手機一般都標配有兩顆攝像頭。在 Camera 中都存在攝像頭切換的功能。

並且有一些功能前後置攝像頭上會有所不同。譬如人臉檢測,人臉識別,自動對焦,閃光燈等功能,

如果前置攝像頭的畫素太低,不支援該功能的話,就需要在前置攝像頭上關掉該 feature.

那麼是如何判斷並切換前後置攝像頭的呢?

我們先來看下 CameraInfo 這個類,

    /**
     * Information about a camera
     */
    public static class CameraInfo {
        /**
         * The facing of the camera is opposite to that of the screen.
         */
        public static final int CAMERA_FACING_BACK = 0;

        /**
         * The facing of the camera is the same as that of the screen.
         */
        public static final int CAMERA_FACING_FRONT = 1;

        /**
         * The direction that the camera faces. It should be
         * CAMERA_FACING_BACK or CAMERA_FACING_FRONT.
         */
        public int facing;

        /**
         * <p>The orientation of the camera image. The value is the angle that the
         * camera image needs to be rotated clockwise so it shows correctly on
         * the display in its natural orientation. It should be 0, 90, 180, or 270.</p>
         *
         * <p>For example, suppose a device has a naturally tall screen. The
         * back-facing camera sensor is mounted in landscape. You are looking at
         * the screen. If the top side of the camera sensor is aligned with the
         * right edge of the screen in natural orientation, the value should be
         * 90. If the top side of a front-facing camera sensor is aligned with
         * the right of the screen, the value should be 270.</p>
         *
         * @see #setDisplayOrientation(int)
         * @see Parameters#setRotation(int)
         * @see Parameters#setPreviewSize(int, int)
         * @see Parameters#setPictureSize(int, int)
         * @see Parameters#setJpegThumbnailSize(int, int)
         */
        public int orientation;
    };
見名知義,它就是一個 Camera 資訊類。它是通過與螢幕的方向是否一致來定義前後置攝像頭的。

與螢幕方向相反即為 BACK_FACING_CAMERA

與螢幕方向一致即為 FRONT_FACING_CAMERA

那麼在程式碼中我們是如何獲取當前使用的 CamerInfo 呢

        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
當然,使用該程式碼的前提是要 import android.hardware.Camera.CameraInfo;

判斷使用是前置還是後置攝像頭,可以通過if (info.facing == CameraInfo.CAMERA_FACING_FRONT) 來判斷。

當Camera 的例項已經建立了的情況下,則需要通過如下方式來判斷。

            CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId];
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                //stopFaceDetection();
            }

也可以通過 if(mCameraId == CameraInfo.CAMERA_FACING_FRONT) 來判斷。

其中 mCameraId 是當前使用的 CameraId, 一般前置為1, 後置為 0。