get Camera Optimal Preview Size - Android Camera

Android examples for Camera:Camera Preview

Description

get Camera Optimal Preview Size

Demo Code


//package com.java2s;
import android.hardware.Camera;

import java.util.List;

public class Main {
    private static final double ASPECT_TOLERANCE = 0.1;

    public static Camera.Size getOptimalPreviewSize(int displayOrientation,
            int width, int height, Camera.Parameters parameters) {
        double targetRatio = (double) width / height;
        List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
        Camera.Size optimalSize = null;// ww w  .j  a  va2 s .com
        double minDiff = Double.MAX_VALUE;
        int targetHeight = height;

        if (displayOrientation == 90 || displayOrientation == 270) {
            targetRatio = (double) height / width;
        }

        // Try to find an size match aspect ratio and size

        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;

            if (Math.abs(ratio - targetRatio) <= ASPECT_TOLERANCE) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }

        // Cannot find the one match the aspect ratio, ignore
        // the requirement

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

Related Tutorials