Search code examples
javaandroidkotlinandroid-cameraandroid-camera2

How to get focal length of camera in Android using Java


I am suppose to get focal length of Camera. My target API version is 21+. I tried the following with help of the documentation:

import android.hardware.Camera;

private float getFocalLengthHere() {

    float focalLength = Camera.Parameters.getFocalLength ();  
    return  focalLength;
}

I encountered the following error:

Non-static method 'getFocalLength()' cannot be referenced from a static context

Here is attached image

In documentation, I didn't found anything to call Focal Length with camera2.


Solution

  • You need to open the camera device, and get a Parameter object first, then call getFocalLength on it:

       Camera myCamera = Camera.open(<camera id>);
       float focalLength = myCamera.getParameters().getFocalLength();
       myCamera.close();
    

    But that's the deprecated camera API. With the newer Camera2 API, you can do:

       CameraCharacteristics = CameraManager.getCameraCharacteristics(<camera id>);
       float focalLength = CameraCharacteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)[0];
    

    which is faster since you don't have to turn on the camera to get the info. Note that a camera that supports physical zooming may have more than one focal length listed; the first one is the default.