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 boolean setOptimalCameraPreviewSize(Camera camera, int width, int height) {
        if (camera == null) {
            return false;
        }

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

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

        List<String> focusModes = params.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        }

        // for Mi3, only support ImageFormat.NV21
        // for most cameras, ImageFormat.NV21 are support worldwide
        // so use default preview format
        // params.setPreviewFormat(ImageFormat.JPEG);
        camera.setParameters(params);
        return true;
    }
}