setPreviewSize() bug in Android?

2019-07-22 00:25发布

问题:

I have the following code in my app:

camera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);

Camera.Parameters setting_param = camera.getParameters();

setting_param.setPreviewSize(128,128);

camera.setParameters(setting_param);

Camera.Parameters read_param = camera.getParameters();

Camera.Size sz = read_param.getPreviewSize();

The code works exactly as expected on my galaxy tab 10.1 running Android 3.1. but on My Galaxy S II phone running 4.1.2, the width and height of the preview, i.e. sz.width and sz.height are 640 and 480! Is this a bug in 4.1.2, or a consequence of an error of mine I am getting away with in 3.1 and not getting away with in 4.1.2?

回答1:

Mick, you should check if a preview size is supported by camera before setting it. Change your onSurfaceChanged method a bit like following.

 public void surfaceChanged(SurfaceHolder holder, int format, int width,
    int height) {

   Camera.Parameters mParameters = mCamera.getParameters();
   Camera.Size bestSize = null;

   List<Camera.Size> sizeList = mCamera.getParameters().getSupportedPreviewSizes();
   bestSize = sizeList.get(0);

     for(int i = 1; i < sizeList.size(); i++){
      if((sizeList.get(i).width * sizeList.get(i).height) >
        (bestSize.width * bestSize.height)){
       bestSize = sizeList.get(i);
      }
     }

     mParameters.setPreviewSize(bestSize.width, bestSize.height);
     mCamera.setParameters(mParameters);
     mCamera.startPreview();

         //any other code ....
    } 


回答2:

Before setting a preview size you should check if that preview size is supported. You have a method on Camera called getSupportedPreviewSizes which will return you a list of supported preview sizes.