相机预览

时间:2015-11-17 11:11:25

标签: android camera android-camera preview aspect-ratio

我知道这个主题在SO上出现了很多次,但是我无法让任何解决方案起作用。我正在构建一个照相亭类型应用程序,除了相机的实时视图失真(图像从上到下拖动)之外,每件事情都正常工作,这会影响最终结果,因为叠加不会仅仅因为相机预览而失真。图像也以正确的宽高比保存。贝娄是代码,如果需要,我可以发布更多。

Parameters params = camera.getParameters();
List<Camera.Size> supportedPreviewSizes = params.getSupportedPreviewSizes();
Camera.Size camPreviewSize = getOptimalPreviewSize(supportedPreviewSizes, width , height);

Log.d(TAG+"--",height +" : " + width);//display height and width
Log.d(TAG+"--",camPreviewSize.height +" : " + camPreviewSize.width);


params.setPreviewSize(camPreviewSize.width ,camPreviewSize.height);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();

计算预览尺寸

private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio=(double)h / w;

    if (sizes == null) return null;

    Camera.Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Camera.Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }
    return optimalSize;
}

更改params.setPreviewSize()的值似乎无效

1 个答案:

答案 0 :(得分:1)

为了回答我自己的问题,在开始相机预览之前我错过了一行。 camera.setParameters(params);

所以我的第一个块应该是这样的。

Parameters params = camera.getParameters();
List<Camera.Size> supportedPreviewSizes = params.getSupportedPreviewSizes();
Camera.Size camPreviewSize = getOptimalPreviewSize(supportedPreviewSizes, width , height);

Log.d(TAG+"--",height +" : " + width);//display height and width
Log.d(TAG+"--",camPreviewSize.height +" : " + camPreviewSize.width);


params.setPreviewSize(camPreviewSize.width ,camPreviewSize.height);

camera.setParameters(params); //This line was missing

camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();