get Camera Optimal Preview Size - Android android.hardware

Android examples for android.hardware:Camera Preview

Description

get Camera Optimal Preview Size

Demo Code

import java.util.List;

import android.hardware.Camera;

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) {/*from ww  w  . j a v a  2  s. c o  m*/
    double targetRatio = (double) width / height;
    List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
    Camera.Size optimalSize = null;
    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