Updates the Camera object's preview size to the nearest match for the given width and height. - Android Camera

Android examples for Camera:Camera Preview

Description

Updates the Camera object's preview size to the nearest match for the given width and height.

Demo Code


//package com.java2s;
import java.lang.reflect.Method;

import java.util.List;

import android.hardware.Camera;

public class Main {

    public static Camera.Size setNearestCameraPreviewSize(Camera camera,
            int width, int height) {
        Camera.Parameters params = camera.getParameters();
        Camera.Size size = bestCameraSizeForWidthAndHeight(params, width,
                height);/*from  ww w .j a va 2 s .co  m*/
        if (size != null) {
            params.setPreviewSize(size.width, size.height);
            camera.setParameters(params);
        }
        return params.getPreviewSize();
    }

    public static Camera.Size bestCameraSizeForWidthAndHeight(
            Camera.Parameters params, int width, int height) {
        List<Camera.Size> previewSizes = previewSizesForCameraParameters(params);
        if (previewSizes == null || previewSizes.size() == 0)
            return null;

        Camera.Size bestSize = null;
        int bestDiff = 0;

        for (Camera.Size size : previewSizes) {
            int diff = Math.abs(size.width - width)
                    + Math.abs(size.height - height);
            if (bestSize == null || diff < bestDiff) {
                bestSize = size;
                bestDiff = diff;
            }
        }
        return bestSize;
    }
    public static List<Camera.Size> previewSizesForCameraParameters(
            Camera.Parameters params) {
        try {
            Method m = params.getClass().getMethod(
                    "getSupportedPreviewSizes");
            return (List<Camera.Size>) m.invoke(params);
        } catch (Exception ex) {
            return null;
        }
    }
}

Related Tutorials