get Optimal Preview Size - Android android.hardware

Android examples for android.hardware:Camera Preview

Description

get Optimal Preview Size

Demo Code

import java.util.List;

import android.hardware.Camera;
import android.hardware.Camera.Size;

public class Main {

  public static Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.1;
    final double MAX_DOWNSIZE = 1.5;

    double targetRatio = (double) w / h;
    if (sizes == null)
      return null;

    Size optimalSize = null;//  w  ww.  j a v  a 2s. c  om
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    // Try to find an size match aspect ratio and size
    for (Camera.Size size : sizes) {
      double ratio = (double) size.width / size.height;
      double downsize = (double) size.width / w;
      if (downsize > MAX_DOWNSIZE) {

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

    if (optimalSize == null) {
      minDiff = Double.MAX_VALUE;
      for (Size size : sizes) {
        double downsize = (double) size.width / w;
        if (downsize > MAX_DOWNSIZE) {
          continue;
        }
        if (Math.abs(size.height - targetHeight) < minDiff) {
          optimalSize = size;
          minDiff = Math.abs(size.height - targetHeight);
        }
      }
    }
    // everything else failed, just take the closest match
    if (optimalSize == null) {
      minDiff = Double.MAX_VALUE;
      for (Size size : sizes) {
        if (Math.abs(size.height - targetHeight) < minDiff) {
          optimalSize = size;
          minDiff = Math.abs(size.height - targetHeight);
        }
      }
    }
    return optimalSize;
  }

}

Related Tutorials