获取android设备相机的分辨率

时间:2019-04-07 17:03:22

标签: java android android-camera2

我正在尝试使用带有StreamConfigurationMap getOutputSizes(ImageFormat.RAW_SENSOR)[0]的android.hardware.camera2中的CameraManager获得设备相机的最大分辨率。它适用于API的22和24,但不能超过25+。在较新的android版本上获得最大相机分辨率的方法是什么?

CameraManager manager = (CameraManager) getActivity().getSystemService(CAMERA_SERVICE);

            try {
                for (String cameraId : manager.getCameraIdList()) {
                    CameraCharacteristics chars = manager.getCameraCharacteristics(cameraId);

                    StreamConfigurationMap streamConfigurationMap = chars.get(
                            CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                    //Log.d(TAG, "onCreate: " + (streamConfigurationMap.getOutputSizes(ImageFormat.RAW_SENSOR)[0]));
                    String mp = streamConfigurationMap.getOutputSizes(ImageFormat.RAW_SENSOR)[0].toString();
                    String[] mpX = mp.split("x");
                    float x = Float.parseFloat(mpX[0]);
                    float y = Float.parseFloat(mpX[1]);
                    double xy = (double) (x * y) / 1000000;

               Log.d(TAG, "onCreate:" + Math.round(xy * 100.0) / 100.0); // here i get resolution in megapixels
                }
            } catch (CameraAccessException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }

如果我使用

  

ImageFormat.JPG

它给了我一些值,但它们不是相机的分辨率。

1 个答案:

答案 0 :(得分:0)

尝试这样。

CameraManager cameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
for (final String cameraId : cameraManager.getCameraIdList()) {

    CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
    StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
    Size[] sizes = streamConfigurationMap.getOutputSizes(ImageFormat.RAW_SENSOR);
    Log.d(TAG, "onCreate:" + getCameraMP(sizes);

}

private String getCameraMP(Size[] size) {
    String finalCameraRes = getMP(size[0], 1);
    int maxSize = size[0].getHeight() * size[0].getWidth();
    for (Size camSize : size) {
        int tempMax = camSize.getHeight() * camSize.getWidth();
        if (tempMax > maxSize) {
            maxSize = tempMax;
            finalCameraRes = getMP(camSize, 1);
        }
    }
    return finalCameraRes;
}

private String getMP(Size size, int decimalPlaces) {
    float mp = (size.getWidth() * size.getHeight()) / 1000000f;
    if (decimalPlaces == 1) {
        return String.format(Locale.US, "%.1f", mp) + " MP";
    } else if (decimalPlaces == 2) {
        return String.format(Locale.US, "%.2f", mp) + " MP";
    } else {
        return String.format(Locale.US, "%.2f", mp) + " MP";
    }
}

即使未授予摄像头许可,这也将在几乎所有Android 5.0+设备上运行。