Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.List;

import android.hardware.Camera;

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

    public static Camera.Size getOptimalCameraPreviewSize(Camera camera, int width, int height) {
        if (camera == null) {
            return null;
        }

        double targetRatio = (double) height / width;

        Camera.Parameters params = camera.getParameters();
        List<Camera.Size> sizes = params.getSupportedPreviewSizes();

        Camera.Size optimalSize = null;

        // selecting optimal camera preview size
        int minDiff = Integer.MAX_VALUE;
        for (Camera.Size size : sizes) {
            double ratio = (double) size.height / size.width;
            if (Math.abs(ratio - targetRatio) > RATIO_TOLERANCE)
                continue;
            if (Math.abs(size.height - height) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - height);
            }
        }

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