Android Camera.Parameters setPictureSize 无效

Android Camera.Parameters setPictureSize not working

我正在尝试在我的相机对象中设置最佳可能的输出图片尺寸。这样,我就可以得到一个完美的缩小样本图像并显示它。

在调试过程中,我观察到我将输出图片大小设置为与我的屏幕尺寸完全一致。但是当我 DecodeBounds 的相机返回的图像。我得到了一些更大的数字!

此外,我没有将显示尺寸设置为预期的输出图片大小。 下面给出了用于计算和设置输出图片大小的代码。

我将此代码用于 API 级别 < 21 的设备,因此使用相机应该不是问题。

我不知道为什么我会出现这种行为。在此先感谢您的帮助!

定义相机参数

Camera.Parameters parameters = mCamera.getParameters();
setOutputPictureSize(parameters.getSupportedPictureSizes(), parameters); //update paramters in this function.

//set the modified parameters back to mCamera
mCamera.setParameters(parameters);

最优图片尺寸计算

private void setOutputPictureSize(List<Camera.Size> availablePicSize, Camera.Parameters parameters)
{
    if (availablePicSize != null) {

        int bestScore = (1<<30); //set an impossible value.
        Camera.Size bestPictureSize = null;

        for (Camera.Size pictureSize : availablePicSize) {

            int curScore = calcOutputScore(pictureSize); //calculate sore of the current picture size
            if (curScore < bestScore) { //update best picture size
                bestScore = curScore;
                bestPictureSize = pictureSize;
            }
        }
        if (bestPictureSize != null) {
            parameters.setPictureSize(bestPictureSize.width, bestPictureSize.height);
        }
    }
}

//calculates score of a target picture size compared to screen dimensions.
//scores are non-negative where 0 is the best score.
private int calcOutputScore(Camera.Size pictureSize)
{
    Point displaySize = AppData.getDiaplaySize();
    int score = (1<<30);//set an impossible value.

    if (pictureSize.height < displaySize.x || pictureSize.width < displaySize.y) {
        return score;  //return the worst possible score.
    }

    for (int i = 1; ; ++i) {

        if (displaySize.x * i > pictureSize.height || displaySize.y * i > pictureSize.width) {
            break;
        }
        score = Math.min(score, Math.max(pictureSize.height-displaySize.x*i, pictureSize.width-displaySize.y*i));
    }
    return score;
}

经过多次尝试终于解决了这个问题!以下是我的发现:

步骤 1. 如果我们已经在预览,请调用 mCamera.stopPreview()

步骤 2. 通过调用 mCamera.setParameters(...)

设置修改参数

步骤3.再次开始预览,调用mCamera.startPreview()

如果我在不停止预览的情况下调用 mCamera.setParameters(假设相机正在预览)。相机似乎忽略了更新的参数。

经过多次尝试和错误,我想出了这个解决方案。谁知道在预览期间更新参数的更好方法,请分享。