下面列出了怎么用android.hardware.camera2.params.StreamConfigurationMap的API类实例代码及写法,或者点击链接到github查看源代码。
public void forceScanAllCameras(Activity activity) {
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
String[] idList = manager.getCameraIdList();
int maxCameraCnt = idList.length;
for (int index = 0; index < maxCameraCnt; index++) {
String cameraId = manager.getCameraIdList()[index];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@TargetApi(21)
public static Size[] querySupportResolution(Context context, int index) {
CameraManager manager =
(CameraManager)context.getSystemService(CAMERA_SERVICE);
try {
CameraCharacteristics chars
= manager.getCameraCharacteristics(index+"");
StreamConfigurationMap configurationMap = chars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
return configurationMap.getOutputSizes(ImageFormat.YUV_420_888);
} catch(CameraAccessException e){
e.printStackTrace();
}
return null;
}
public Size configureCamera(int width, int height) {
try {
mCameraIdStr = CameraUtils.getRearCameraId(mCameraManager);
mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraIdStr);
sensorArraySize = mCameraCharacteristics.get(
CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
StreamConfigurationMap map = mCameraCharacteristics.get(CameraCharacteristics
.SCALER_STREAM_CONFIGURATION_MAP);
mVideoSize = CameraUtils.chooseVideoSize(
map.getOutputSizes(MediaRecorder.class), width, height, width);
mFocalLengthHelper.setLensParams(mCameraCharacteristics);
mFocalLengthHelper.setmImageSize(mVideoSize);
mPreviewSize = CameraUtils.chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
width, height, mVideoSize);
Log.d(TAG, "Video size " + mVideoSize.toString() +
" preview size " + mPreviewSize.toString());
} catch (CameraAccessException e) {
e.printStackTrace();
}
return mPreviewSize;
}
private void setupCamera(int width, int height) {
try {
for (String camId: cameraManager.getCameraIdList()) {
CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(camId);
if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == cameraFacing) {
StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
previewSize = chooseOptimalSize(streamConfigurationMap.getOutputSizes(SurfaceTexture.class),
streamConfigurationMap.getOutputSizes(ImageFormat.JPEG), width, height);
cameraId = camId;
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @return The largest supported picture size.
*/
public Size getDefaultPictureSize()
{
StreamConfigurationMap configs =
mCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
android.util.Size[] supportedSizes = configs.getOutputSizes(sCaptureImageFormat);
// Find the largest supported size.
android.util.Size largestSupportedSize = supportedSizes[0];
long largestSupportedSizePixels =
largestSupportedSize.getWidth() * largestSupportedSize.getHeight();
for (int i = 0; i < supportedSizes.length; i++)
{
long numPixels = supportedSizes[i].getWidth() * supportedSizes[i].getHeight();
if (numPixels > largestSupportedSizePixels)
{
largestSupportedSize = supportedSizes[i];
largestSupportedSizePixels = numPixels;
}
}
return new Size(largestSupportedSize.getWidth(), largestSupportedSize.getHeight());
}
@Override
public List<Size> getSupportedPictureSizes(int imageFormat)
{
StreamConfigurationMap configMap;
try
{
configMap = mCameraCharacteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
} catch (Exception ex)
{
Log.e(TAG, "Unable to obtain picture sizes.", ex);
// See b/19623115 where java.lang.AssertionError can be thrown due to HAL error
return new ArrayList<>(0);
}
ArrayList<Size> supportedPictureSizes = new ArrayList<>();
for (android.util.Size androidSize : configMap.getOutputSizes(imageFormat))
{
supportedPictureSizes.add(new Size(androidSize));
}
return supportedPictureSizes;
}
@Override
public List<Size> getSupportedPreviewSizes()
{
StreamConfigurationMap configMap;
try
{
configMap = mCameraCharacteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
} catch (Exception ex)
{
Log.e(TAG, "Unable to obtain preview sizes.", ex);
// See b/19623115 where java.lang.AssertionError can be thrown due to HAL error
return new ArrayList<>(0);
}
ArrayList<Size> supportedPictureSizes = new ArrayList<>();
for (android.util.Size androidSize : configMap.getOutputSizes(SurfaceTexture.class))
{
supportedPictureSizes.add(new Size(androidSize));
}
return supportedPictureSizes;
}
/**
* @return The largest supported picture size.
*/
public Size getDefaultPictureSize()
{
StreamConfigurationMap configs = mCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
android.util.Size[] supportedSizes = configs.getOutputSizes(sCaptureImageFormat);
// Find the largest supported size.
android.util.Size largestSupportedSize = supportedSizes[0];
long largestSupportedSizePixels = largestSupportedSize.getWidth() * largestSupportedSize.getHeight();
for (int i = 1; i < supportedSizes.length; i++)
{
long numPixels = supportedSizes[i].getWidth() * supportedSizes[i].getHeight();
if (numPixels > largestSupportedSizePixels)
{
largestSupportedSize = supportedSizes[i];
largestSupportedSizePixels = numPixels;
}
}
return new Size(largestSupportedSize.getWidth(), largestSupportedSize.getHeight());
}
@SuppressLint("MissingPermission")
public void openCamera(int width, int height) {
Log.v(TAG, "openCamera");
startBackgroundThread(); // 对应 releaseCamera() 方法中的 stopBackgroundThread()
mOrientationEventListener.enable();
try {
mCameraCharacteristics = mCameraManager.getCameraCharacteristics(Integer.toString(mCameraId));
StreamConfigurationMap map = mCameraCharacteristics.get(CameraCharacteristics
.SCALER_STREAM_CONFIGURATION_MAP);
// 拍照大小,选择能支持的一个最大的图片大小
Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new
CompareSizesByArea());
Log.d(TAG, "picture size: " + largest.getWidth() + "*" + largest.getHeight());
mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, 2);
// 预览大小,根据上面选择的拍照图片的长宽比,选择一个和控件长宽差不多的大小
mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, largest);
Log.d(TAG, "preview size: " + mPreviewSize.getWidth() + "*" + mPreviewSize.getHeight());
// 打开摄像头
mCameraManager.openCamera(Integer.toString(mCameraId), mStateCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
public Size[] getSupportedPictureSizes(String cameraId) {
Size[] outputSizes = null;
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
outputSizes = map.getOutputSizes(ImageFormat.JPEG);
}
} catch (CameraAccessException e) {
Log.w(TAG, e);
}
return outputSizes;
}
@Override
public void setDeviceRotation(int deviceOrientation) {
mDeviceOrientation = deviceOrientation;
// configure transform if preview is running only
if (isPreviewRunning()) {
try {
CameraCharacteristics characteristics = mCamManager.getCameraCharacteristics(mCamera.getId());
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
Log.w(TAG, "Could not find a valid preview size");
} else {
final Point previewSize = chooseOptimalSize(toPointArray(map.getOutputSizes(ImageFormat.YUV_420_888)));
setDeviceOrientation(previewSize);
}
} catch (CameraAccessException e) {
Log.e(TAG, "Failed to set device orientation", e);
}
}
}
public Size[] getCameraResolutions(Facing facing) {
try {
CameraCharacteristics characteristics = getCharacteristicsForFacing(cameraManager, facing);
if (characteristics == null) {
return new Size[0];
}
StreamConfigurationMap streamConfigurationMap =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] outputSizes = streamConfigurationMap.getOutputSizes(SurfaceTexture.class);
return outputSizes != null ? outputSizes : new Size[0];
} catch (CameraAccessException | NullPointerException e) {
Log.e(TAG, "Error", e);
return new Size[0];
}
}
/**
* 指定した条件に合う解像度を選択する
* @param manager
* @param cameraId
* @param targetFace
* @param width
* @param height
* @param degrees
* @return
* @throws CameraAccessException
*/
public static CameraConst.CameraInfo chooseOptimalSize(
@NonNull final CameraManager manager,
final String cameraId, @CameraConst.FaceType final int targetFace,
final int width, final int height, final int degrees)
throws CameraAccessException {
if (DEBUG) Log.v(TAG,
String.format("chooseOptimalSize:Size(%dx%d),targetFace=%d,degrees=%d",
width, height, targetFace, degrees));
final CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
final StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
final Size previewSize
= chooseOptimalSize(characteristics, map, width, height, degrees);
final int orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
if (!TextUtils.isEmpty(cameraId) && (previewSize != null)) {
return new CameraConst.CameraInfo(cameraId, targetFace, orientation,
previewSize.getWidth(), previewSize.getHeight());
}
return null;
}
@Override
protected List<PreviewSize> getSupportedSize() {
try {
CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(
getCurrentCameraId());
StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
return Collections.singletonList(new PreviewSize(mPreviewWidth, mPreviewHeight));
}
Size[] supportedSize = map.getOutputSizes(SurfaceTexture.class);
if (supportedSize == null || supportedSize.length == 0) {
return Collections.singletonList(new PreviewSize(mPreviewWidth, mPreviewHeight));
}
List<PreviewSize> results = new ArrayList<>();
for (Size size : supportedSize) {
results.add(new PreviewSize(size.getWidth(), size.getHeight()));
}
return results;
} catch (CameraAccessException e) {
throw new CameraAccessError();
}
}
/**
* <p>Collects some information from {@link #mCameraCharacteristics}.</p>
* <p>This rewrites {@link #mPreviewSizes}, {@link #mPictureSizes}, and optionally,
* {@link #mAspectRatio}.</p>
*/
private void collectCameraInfo() {
StreamConfigurationMap map = mCameraCharacteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
throw new IllegalStateException("Failed to get configuration map: " + mCameraId);
}
mPreviewSizes.clear();
for (android.util.Size size : map.getOutputSizes(mPreview.getOutputClass())) {
mPreviewSizes.add(new Size(size.getWidth(), size.getHeight()));
}
mPictureSizes.clear();
collectPictureSizes(mPictureSizes, map);
if (!mPreviewSizes.ratios().contains(mAspectRatio)) {
mAspectRatio = mPreviewSizes.ratios().iterator().next();
}
}
/**
* カメラID に対応したカメラデバイスがサポートしているプレビューサイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしているプレビューサイズのリスト
*/
@NonNull
public static List<Size> getSupportedPreviewSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> previewSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
previewSizes = Arrays.asList(map.getOutputSizes(SurfaceTexture.class));
Collections.sort(previewSizes, SizeComparator);
}
} catch (CameraAccessException e) {
// ignore.
}
return previewSizes;
}
/**
* カメラID に対応したカメラデバイスがサポートしている写真サイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしている写真サイズのリスト
*/
@NonNull
public static List<Size> getSupportedPictureSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> pictureSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if(map != null) {
pictureSizes = Arrays.asList(map.getOutputSizes(ImageFormat.YUV_420_888));
Collections.sort(pictureSizes, SizeComparator);
}
} catch (CameraAccessException e) {
// ignore.
}
return pictureSizes;
}
/**
* カメラID に対応したカメラデバイスがサポートしているプレビューサイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしているプレビューサイズのリスト
*/
@NonNull
static List<Size> getSupportedPreviewSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> previewSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
previewSizes = Arrays.asList(map.getOutputSizes(SurfaceTexture.class));
Collections.sort(previewSizes, SizeComparator);
}
} catch (CameraAccessException e) {
// ignore.
}
return previewSizes;
}
/**
* カメラID に対応したカメラデバイスがサポートしている写真サイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしている写真サイズのリスト
*/
@NonNull
static List<Size> getSupportedPictureSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> pictureSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if(map != null) {
pictureSizes = Arrays.asList(map.getOutputSizes(ImageFormat.JPEG));
Collections.sort(pictureSizes, SizeComparator);
}
} catch (CameraAccessException e) {
// ignore.
}
return pictureSizes;
}
/**
* カメラID に対応したカメラデバイスがサポートしているプレビューサイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしているプレビューサイズのリスト
*/
@NonNull
private static List<Size> getSupportedPreviewSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> previewSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
previewSizes = Arrays.asList(map.getOutputSizes(SurfaceTexture.class));
Collections.sort(previewSizes, SIZE_COMPARATOR);
}
} catch (CameraAccessException e) {
// ignore.
}
return previewSizes;
}
/**
* カメラID に対応したカメラデバイスがサポートしているプレビューサイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしているプレビューサイズのリスト
*/
@NonNull
static List<Size> getSupportedPreviewSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> previewSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
previewSizes = Arrays.asList(map.getOutputSizes(SurfaceTexture.class));
Collections.sort(previewSizes, SIZE_COMPARATOR);
}
} catch (CameraAccessException e) {
// ignore.
}
return previewSizes;
}
/**
* カメラID に対応したカメラデバイスがサポートしている写真サイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしている写真サイズのリスト
*/
@NonNull
static List<Size> getSupportedPictureSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> pictureSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if(map != null) {
pictureSizes = Arrays.asList(map.getOutputSizes(ImageFormat.JPEG));
Collections.sort(pictureSizes, SIZE_COMPARATOR);
}
} catch (CameraAccessException e) {
// ignore.
}
return pictureSizes;
}
static List<Size> getSupportedSizes(CameraCharacteristics cameraCharacteristics) {
final StreamConfigurationMap streamMap =
cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
final int supportLevel =
cameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
final android.util.Size[] nativeSizes = streamMap.getOutputSizes(SurfaceTexture.class);
final List<Size> sizes = convertSizes(nativeSizes);
// Video may be stretched pre LMR1 on legacy implementations.
// Filter out formats that have different aspect ratio than the sensor array.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1
&& supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
final Rect activeArraySize =
cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
final ArrayList<Size> filteredSizes = new ArrayList<Size>();
for (Size size : sizes) {
if (activeArraySize.width() * size.height == activeArraySize.height() * size.width) {
filteredSizes.add(size);
}
}
return filteredSizes;
} else {
return sizes;
}
}
@Override
public void marshal(ReprocessFormatsMap value, ByteBuffer buffer) {
/*
* // writing (static example, DNG+ZSL)
* int32_t[] contents = {
* RAW_OPAQUE, 3, RAW16, YUV_420_888, BLOB,
* RAW16, 2, YUV_420_888, BLOB,
* ...,
* INPUT_FORMAT, OUTPUT_FORMAT_COUNT, [OUTPUT_0, OUTPUT_1, ..., OUTPUT_FORMAT_COUNT-1]
* };
*/
int[] inputs = StreamConfigurationMap.imageFormatToInternal(value.getInputs());
for (int input : inputs) {
// INPUT_FORMAT
buffer.putInt(input);
int[] outputs =
StreamConfigurationMap.imageFormatToInternal(value.getOutputs(input));
// OUTPUT_FORMAT_COUNT
buffer.putInt(outputs.length);
// [OUTPUT_0, OUTPUT_1, ..., OUTPUT_FORMAT_COUNT-1]
for (int output : outputs) {
buffer.putInt(output);
}
}
}
private StreamConfigurationMap getStreamConfigurationMap() {
StreamConfiguration[] configurations = getBase(
CameraCharacteristics.SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
StreamConfigurationDuration[] minFrameDurations = getBase(
CameraCharacteristics.SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
StreamConfigurationDuration[] stallDurations = getBase(
CameraCharacteristics.SCALER_AVAILABLE_STALL_DURATIONS);
StreamConfiguration[] depthConfigurations = getBase(
CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_STREAM_CONFIGURATIONS);
StreamConfigurationDuration[] depthMinFrameDurations = getBase(
CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_MIN_FRAME_DURATIONS);
StreamConfigurationDuration[] depthStallDurations = getBase(
CameraCharacteristics.DEPTH_AVAILABLE_DEPTH_STALL_DURATIONS);
HighSpeedVideoConfiguration[] highSpeedVideoConfigurations = getBase(
CameraCharacteristics.CONTROL_AVAILABLE_HIGH_SPEED_VIDEO_CONFIGURATIONS);
ReprocessFormatsMap inputOutputFormatsMap = getBase(
CameraCharacteristics.SCALER_AVAILABLE_INPUT_OUTPUT_FORMATS_MAP);
int[] capabilities = getBase(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);
boolean listHighResolution = false;
for (int capability : capabilities) {
if (capability == CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_BURST_CAPTURE) {
listHighResolution = true;
break;
}
}
return new StreamConfigurationMap(
configurations, minFrameDurations, stallDurations,
depthConfigurations, depthMinFrameDurations, depthStallDurations,
highSpeedVideoConfigurations, inputOutputFormatsMap,
listHighResolution);
}
private void checkInputConfiguration(InputConfiguration inputConfig) {
if (inputConfig != null) {
StreamConfigurationMap configMap = mCharacteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
int[] inputFormats = configMap.getInputFormats();
boolean validFormat = false;
for (int format : inputFormats) {
if (format == inputConfig.getFormat()) {
validFormat = true;
}
}
if (validFormat == false) {
throw new IllegalArgumentException("input format " + inputConfig.getFormat() +
" is not valid");
}
boolean validSize = false;
Size[] inputSizes = configMap.getInputSizes(inputConfig.getFormat());
for (Size s : inputSizes) {
if (inputConfig.getWidth() == s.getWidth() &&
inputConfig.getHeight() == s.getHeight()) {
validSize = true;
}
}
if (validSize == false) {
throw new IllegalArgumentException("input size " + inputConfig.getWidth() + "x" +
inputConfig.getHeight() + " is not valid");
}
}
}
private String chooseCamera() {
final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
for (final String cameraId : manager.getCameraIdList()) {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
final StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
// Fallback to camera1 API for internal cameras that don't have full support.
// This should help with legacy situations where using the camera2 API causes
// distorted or otherwise broken previews.
useCamera2API = (facing == CameraCharacteristics.LENS_FACING_EXTERNAL)
|| isHardwareLevelSupported(characteristics,
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL);
return cameraId;
}
} catch (CameraAccessException e) {
Log.e("CameraAccessException", "Not allowed to access camera" + e.toString());
}
return null;
}
/**
* <p>Collects some information from {@link #mCameraCharacteristics}.</p>
* <p>This rewrites {@link #mPreviewSizes}, {@link #mPictureSizes}, and optionally,
* {@link #mAspectRatio}.</p>
*/
private void collectCameraInfo() {
StreamConfigurationMap map = mCameraCharacteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
throw new IllegalStateException("Failed to get configuration map: " + mCameraId);
}
mPreviewSizes.clear();
for (android.util.Size size : map.getOutputSizes(mPreview.getOutputClass())) {
int width = size.getWidth();
int height = size.getHeight();
if (width <= MAX_PREVIEW_WIDTH && height <= MAX_PREVIEW_HEIGHT) {
mPreviewSizes.add(new Size(width, height));
}
}
mPictureSizes.clear();
collectPictureSizes(mPictureSizes, map);
for (AspectRatio ratio : mPreviewSizes.ratios()) {
if (!mPictureSizes.ratios().contains(ratio)) {
mPreviewSizes.remove(ratio);
}
}
if (!mPreviewSizes.ratios().contains(mAspectRatio)) {
mAspectRatio = mPreviewSizes.ratios().iterator().next();
}
}
@Override
protected void collectPictureSizes(SizeMap sizes, StreamConfigurationMap map) {
// Try to get hi-res output sizes
android.util.Size[] outputSizes = map.getHighResolutionOutputSizes(ImageFormat.JPEG);
if (outputSizes != null) {
for (android.util.Size size : map.getHighResolutionOutputSizes(ImageFormat.JPEG)) {
sizes.add(new Size(size.getWidth(), size.getHeight()));
}
}
if (sizes.isEmpty()) {
super.collectPictureSizes(sizes, map);
}
}
/**
* Sets up member variables related to camera.
*/
private void setUpCameraOutputs() {
final Activity activity = getActivity();
final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
final StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
previewSize =
chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
inputSize.getWidth(),
inputSize.getHeight());
// We fit the aspect ratio of TextureView to the size of preview we picked.
final int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
textureView.setAspectRatio(previewSize.getWidth(), previewSize.getHeight());
} else {
textureView.setAspectRatio(previewSize.getHeight(), previewSize.getWidth());
}
} catch (final CameraAccessException ignored) {
} catch (final NullPointerException e) {
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
throw new RuntimeException(getString(R.string.camera_error));
}
cameraConnectionCallback.onPreviewSizeChosen(previewSize, sensorOrientation);
}