2

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?

Mick
  • 8,284
  • 22
  • 81
  • 173

2 Answers2

6

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.

Pasquale Anatriello
  • 2,355
  • 1
  • 16
  • 16
4

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 ....
    } 
Adnan
  • 5,025
  • 5
  • 25
  • 44
  • Note that this algorithm does not take into account the aspect ratio of the surface, and therefore the preview image may be stretched or squashed. I use a different algorithm as my default one in the CWAC-Camera library, as described in http://stackoverflow.com/questions/21354313/camera-preview-quality-in-android-is-poor/21354442#21354442 – CommonsWare Jan 28 '14 at 12:41