setPreviewSize does not work on Nexus 5 kitkat

2019-08-09 08:41发布

In my app i need to set the camera preview size at 640x480. I tried my code on different devices and different android versions (for example 2.3.6 on samsung galaxy S2, 4.0.3 on asus tf101g, 4.3 on galaxy nexus), and at the last on the new Nexus 5 with android kitkat(4.4).

My code works perfectly in all devices, but doesn't work on Nexus 5. Why? In fact after this steps:

int PREVIEW_WIDTH = 640;
int PREVIEW_HEIGHT = 480;
if(isSupportedSize(PREVIEW_WIDTH,PREVIEW_HEIGHT,mCamera)){
//isSupportedSize controls that width and height are supported by mCamera
mCamera.getParameters().setPreviewSize(PREVIEW_WIDTH,PREVIEW_HEIGHT);
Log.d("debug myapp", "Preview sizes: "  + mCamera.getParameters().getPreviewSize().width
                    + ", "
                    + mCamera.getParameters().getPreviewSize().height);
}

or this steps:

int PREVIEW_WIDTH = 640;
int PREVIEW_HEIGHT = 480;
Camera.Parameters param= mCamera.getParameters();
if(isSupportedSize(PREVIEW_WIDTH,PREVIEW_HEIGHT,param)){
//isSupportedSize controls that width and height are supported by mCamera
param.setPreviewSize(PREVIEW_WIDTH,PREVIEW_HEIGHT);
mCamera.setParameters(param);
Log.d("debug myapp", "Preview sizes: "  + mCamera.getParameters().getPreviewSize().width
                    + ", "
                    + mCamera.getParameters().getPreviewSize().height);
}

Only on Nexus5 the Log is 1920, 1080. Why? Has Somebody the same problem?

isSupportedSize():

private boolean isSupportedSize(int width, int height, Camera cam){
    Camera.Parameters param = cam.getParameters();
    List<Size> suppSizes = param.getSupportedPreviewSizes();
    for (Size s: suppSizes){
        if (s.width == width && s.height == height){
            Log.d("debug", "sizes supported!");
            return true;
        }
    }
    return false;
}

It works perfectly.

2条回答
冷血范
2楼-- · 2019-08-09 08:57

See answer to this post. Some tablets seem to allow changing the preview size while in preview mode already while others don't.

查看更多
劳资没心,怎么记你
3楼-- · 2019-08-09 09:00

Have you tried this? Stop the preview and restart it. With this code, in my app, i don't need the function "isSupportedSize". Let me know if you need more help.

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

    if (holder.getSurface() == null) {
        return;
    }

    try {
        mCamera.stopPreview();
    } catch (Exception e) {
        // TODO: handle exception
    }
    try {
        mCamera.setPreviewDisplay(holder);
        Camera.Parameters parameters=mCamera.getParameters();           
        parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
        mCamera.setParameters(parameters);
        mCamera.startPreview();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
查看更多
登录 后发表回答