Android相机:设置图像大小和预览大小

时间:2015-12-09 13:36:30

标签: android camera android-camera surfaceview

在我的相机应用中,我尝试设置预览surfaceViewimagePreviewImage尺寸,但无论我更改什么,实时预览始终占据整个活动。似乎没有任何失真,但问题是我需要附加预览中存在的叠加图像,并且必须保存在最终图像中的相同位置。

当我将params.getPictureSize(). widthheight传递到getOptimalPreviewSize()方法时,不应该根据最终图像尺寸拍摄预览尺寸吗?

surfaceView布局

<FrameLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</FrameLayout>

设置图片尺寸

Parameters params = camera.getParameters();
List <Camera.Size>sizes = params.getSupportedPictureSizes();
if(sizes.size() > 1){
    params.setPictureSize(sizes.get(2).width,sizes.get(2).height);// get can be value 0 - 5
    camera.setParameters(params);
}

注意我在这里手动设置不同的尺寸以进行测试

设置预览尺寸

List<Camera.Size> supportedPreviewSizes = params.getSupportedPreviewSizes();
Camera.Size camPreviewSize = getOptimalPreviewSize(supportedPreviewSizes, params.getPictureSize().width , params.getPictureSize().height);
params.setPreviewSize(camPreviewSize.width, camPreviewSize.height);
camera.setPreviewDisplay(surfaceHolder);
camera.setParameters(params);
camera.startPreview();

getOptimalPreviewSize()

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;
}

0 个答案:

没有答案