android.hardware.camera2.CameraAccessException Java Examples

The following examples show how to use android.hardware.camera2.CameraAccessException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VIACamera.java    From VIA-AI with MIT License 8 votes vote down vote up
@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;
}
 
Example #2
Source File: CameraDeviceImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void stopRepeating() throws CameraAccessException {

        synchronized(mInterfaceLock) {
            checkIfCameraClosedOrInError();
            if (mRepeatingRequestId != REQUEST_ID_NONE) {

                int requestId = mRepeatingRequestId;
                mRepeatingRequestId = REQUEST_ID_NONE;

                long lastFrameNumber;
                try {
                    lastFrameNumber = mRemoteDevice.cancelRequest(requestId);
                } catch (IllegalArgumentException e) {
                    if (DEBUG) {
                        Log.v(TAG, "Repeating request was already stopped for request " + requestId);
                    }
                    // Repeating request was already stopped. Nothing more to do.
                    return;
                }

                checkEarlyTriggerSequenceComplete(requestId, lastFrameNumber);
            }
        }
    }
 
Example #3
Source File: Flashlight.java    From Flashlight-PhoneGap-Plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
private void doToggleTorch(boolean switchOn) throws IOException, CameraAccessException {
  if (Build.VERSION.SDK_INT >= 23) { // Android M has such an easy API! <3
    doToggleTorchSdk23(switchOn);

  } else {
    if (mCamera == null) {
      mCamera = Camera.open();
      if (Build.VERSION.SDK_INT >= 11) { // honeycomb
        // required for (at least) the Nexus 5
        mCamera.setPreviewTexture(new SurfaceTexture(0));
      }
    }
    final Camera.Parameters mParameters = mCamera.getParameters();
    mParameters.setFlashMode(switchOn ? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
    mCamera.setParameters(mParameters);
    mCamera.startPreview();
    callbackContext.success();
  }
}
 
Example #4
Source File: MainActivity.java    From libsoftwaresync with Apache License 2.0 6 votes vote down vote up
private void startPreview() {
  Log.d(TAG, "Starting preview.");

  try {
    CaptureRequest.Builder previewRequestBuilder =
        cameraController
            .getRequestFactory()
            .makePreview(
                viewfinderSurface,
                cameraController.getOutputSurfaces(),
                currentSensorExposureTimeNs,
                currentSensorSensitivity);

    captureSession.stopRepeating();
    captureSession.setRepeatingRequest(
        previewRequestBuilder.build(),
        cameraController.getSynchronizerCaptureCallback(),
        cameraHandler);

  } catch (CameraAccessException e) {
    Log.w(TAG, "Unable to create preview.");
  }
}
 
Example #5
Source File: Camera2Utils.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 指定した条件に合う解像度を選択する
 * @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;
}
 
Example #6
Source File: OBCameraManager.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
private void updatePreview(final OBVideoPlayer videoPlayer)
{
    if (null == cameraDevice)
    {
        return;
    }
    try
    {
        setUpCaptureRequestBuilder(previewBuilder);

        captureSession.setRepeatingRequest(previewBuilder.build(),
                new CameraCaptureSession.CaptureCallback()
                {
                    @Override
                    public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result)
                    {
                        videoPlayer.invalidate();
                        super.onCaptureCompleted(session, request, result);
                    }
                }
                , backgroundHandler);
    } catch (CameraAccessException e)
    {
        e.printStackTrace();
    }
}
 
Example #7
Source File: Camera2.java    From TikTok with Apache License 2.0 6 votes vote down vote up
@Override
void setFlash(int flash) {
    if (mFlash == flash) {
        return;
    }
    int saved = mFlash;
    mFlash = flash;
    if (mPreviewRequestBuilder != null) {
        updateFlash();
        if (mCaptureSession != null) {
            try {
                mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(),
                        mCaptureCallback, null);
            } catch (CameraAccessException e) {
                mFlash = saved; // Revert
            }
        }
    }
}
 
Example #8
Source File: HdrViewfinderActivity.java    From android-HdrViewfinder with Apache License 2.0 6 votes vote down vote up
/**
 * Callbacks for CameraOps
 */
@Override
public void onCameraReady() {
    // Ready to send requests in, so set them up
    try {
        CaptureRequest.Builder previewBuilder =
                mCameraOps.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        previewBuilder.addTarget(mProcessingNormalSurface);
        previewBuilder.setTag(mAutoExposureTag);
        mPreviewRequest = previewBuilder.build();

        mHdrBuilder =
                mCameraOps.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mHdrBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                CaptureRequest.CONTROL_AE_MODE_OFF);
        mHdrBuilder.addTarget(mProcessingHdrSurface);

        switchRenderMode(0);

    } catch (CameraAccessException e) {
        String errorMessage = getErrorString(e);
        showErrorDialog(errorMessage);
    }
}
 
Example #9
Source File: OneCameraImpl.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
/**
 * Request preview capture stream with auto focus trigger cycle.
 */
private void sendAutoFocusTriggerCaptureRequest(Object tag)
{
    try
    {
        // Step 1: Request single frame CONTROL_AF_TRIGGER_START.
        CaptureRequest.Builder builder;
        builder = mDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        builder.addTarget(mPreviewSurface);
        builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        mControlAFMode = CameraMetadata.CONTROL_AF_MODE_AUTO;
        addBaselineCaptureKeysToRequest(builder);
        builder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
        builder.setTag(tag);
        mCaptureSession.capture(builder.build(), mCaptureCallback, mCameraHandler);

        // Step 2: Call repeatingPreview to update mControlAFMode.
        repeatingPreview(tag);
        resumeContinuousAFAfterDelay(FOCUS_HOLD_MILLIS);
    } catch (CameraAccessException ex)
    {
        Log.e(TAG, "Could not execute preview request.", ex);
    }
}
 
Example #10
Source File: CameraActivity.java    From Chinese-number-gestures-recognition with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 拍照
 */
@SuppressLint("NewApi")
private void takePicture() {
    if (mCameraDevice == null) return;
    // 创建拍照需要的CaptureRequest.Builder
    final CaptureRequest.Builder captureRequestBuilder;
    try {
        captureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        // 将imageReader的surface作为CaptureRequest.Builder的目标
        captureRequestBuilder.addTarget(mImageReader.getSurface());
        // 自动对焦
        captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
        // 自动曝光
        captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        // 获取手机方向
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        // 根据设备方向计算设置照片的方向
        captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
        //拍照
        CaptureRequest mCaptureRequest = captureRequestBuilder.build();
        mCameraCaptureSession.capture(mCaptureRequest, null, childHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
 
Example #11
Source File: CameraDeviceImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void flush() throws CameraAccessException {
    synchronized(mInterfaceLock) {
        checkIfCameraClosedOrInError();

        mDeviceExecutor.execute(mCallOnBusy);

        // If already idle, just do a busy->idle transition immediately, don't actually
        // flush.
        if (mIdle) {
            mDeviceExecutor.execute(mCallOnIdle);
            return;
        }

        long lastFrameNumber = mRemoteDevice.flush();
        if (mRepeatingRequestId != REQUEST_ID_NONE) {
            checkEarlyTriggerSequenceComplete(mRepeatingRequestId, lastFrameNumber);
            mRepeatingRequestId = REQUEST_ID_NONE;
        }
    }
}
 
Example #12
Source File: CameraCaptureSessionImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public int setSingleRepeatingRequest(CaptureRequest request, Executor executor,
        CaptureCallback callback) throws CameraAccessException {
    if (executor == null) {
        throw new IllegalArgumentException("executor must not be null");
    } else if (callback == null) {
        throw new IllegalArgumentException("callback must not be null");
    }
    checkRepeatingRequest(request);

    synchronized (mDeviceImpl.mInterfaceLock) {
        checkNotClosed();

        executor = CameraDeviceImpl.checkExecutor(executor, callback);

        if (DEBUG) {
            Log.v(TAG, mIdString + "setRepeatingRequest - request " + request + ", callback " +
                    callback + " executor" + " " + executor);
        }

        return addPendingSequence(mDeviceImpl.setRepeatingRequest(request,
                createCaptureCallbackProxyWithExecutor(executor, callback), mDeviceExecutor));
    }
}
 
Example #13
Source File: Camera2ApiManager.java    From rtmp-rtsp-stream-client-java with Apache License 2.0 6 votes vote down vote up
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];
  }
}
 
Example #14
Source File: AndroidCamera2AgentImpl.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
@Override
public void onOpened(CameraDevice camera) {
    mCamera = camera;
    if (mOpenCallback != null) {
        try {
            CameraCharacteristics props =
                    mCameraManager.getCameraCharacteristics(mCameraId);
            CameraDeviceInfo.Characteristics characteristics =
                    getCameraDeviceInfo().getCharacteristics(mCameraIndex);
            mCameraProxy = new AndroidCamera2ProxyImpl(AndroidCamera2AgentImpl.this,
                    mCameraIndex, mCamera, characteristics, props);
            mPersistentSettings = new Camera2RequestSettingsSet();
            mActiveArray =
                    props.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
            mLegacyDevice =
                    props.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) ==
                            CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
            changeState(AndroidCamera2StateHolder.CAMERA_UNCONFIGURED);
            mOpenCallback.onCameraOpened(mCameraProxy);
        } catch (CameraAccessException ex) {
            mOpenCallback.onDeviceOpenFailure(mCameraIndex,
                    generateHistoryString(mCameraIndex));
        }
    }
}
 
Example #15
Source File: CameraCaptureSessionImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public int captureBurst(List<CaptureRequest> requests, CaptureCallback callback,
        Handler handler) throws CameraAccessException {
    checkCaptureRequests(requests);

    synchronized (mDeviceImpl.mInterfaceLock) {
        checkNotClosed();

        handler = checkHandler(handler, callback);

        if (DEBUG) {
            CaptureRequest[] requestArray = requests.toArray(new CaptureRequest[0]);
            Log.v(TAG, mIdString + "captureBurst - requests " + Arrays.toString(requestArray) +
                    ", callback " + callback + " handler " + handler);
        }

        return addPendingSequence(mDeviceImpl.captureBurst(requests,
                createCaptureCallbackProxy(handler, callback), mDeviceExecutor));
    }
}
 
Example #16
Source File: Camera2Controller.java    From pixelvisualcorecamera with Apache License 2.0 6 votes vote down vote up
/**
 * Unlock the focus. This method should be called when still image capture sequence is
 * finished.
 */
private void unlockFocus() {
  try {
    state = STATE_PREVIEW;

    // Send a single request to cancel any AF in progress.
    setAfTriggerCancel(previewRequestBuilder);
    captureSession.capture(previewRequestBuilder.build(), captureCallback, backgroundHandler);
    setAfTriggerIdle(previewRequestBuilder);

    // After this resume a normal preview.
    captureSession.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler);
  } catch (CameraAccessException e) {
    Log.w(TAG, e);
  }
}
 
Example #17
Source File: Camera2Helper.java    From CameraCompat with MIT License 6 votes vote down vote up
@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();
    }
}
 
Example #18
Source File: VideoCameraActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera() {
  try {
    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String[] cameraIds = cameraManager.getCameraIdList();
    if (cameraIds.length == 0) return;

    String cameraId = cameraIds[0];

    if (ActivityCompat.checkSelfPermission(this,
      Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this,
        new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSIONS_REQUEST);
    }

    cameraManager.openCamera(cameraId, cameraDeviceCallback, null);
  } catch (CameraAccessException e) {
    Log.d(TAG, "No access to the camera.", e);
  }
}
 
Example #19
Source File: Camera2.java    From MediaPickerInstagram with Apache License 2.0 6 votes vote down vote up
@Override
public void setAutoFocus(boolean autoFocus) {
    if (mAutoFocus == autoFocus) {
        return;
    }
    mAutoFocus = autoFocus;
    if (mPreviewRequestBuilder != null) {
        updateAutoFocus();
        if (mCaptureSession != null) {
            try {
                mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(),
                        mCaptureCallback, null);
            } catch (CameraAccessException e) {
                mAutoFocus = !mAutoFocus; // Revert
            }
        }
    }
}
 
Example #20
Source File: OneCameraZslImpl.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
@Override
public void close()
{
    if (mIsClosed)
    {
        Log.w(TAG, "Camera is already closed.");
        return;
    }
    try
    {
        mCaptureSession.stopRepeating();
    } catch (CameraAccessException e)
    {
        Log.e(TAG, "Could not abort captures in progress.");
    }
    mIsClosed = true;
    mCameraThread.quitSafely();
    mDevice.close();
    mCaptureManager.close();
    mCaptureImageReader.close();
}
 
Example #21
Source File: FlashHandler.java    From habpanelviewer with GNU General Public License v3.0 6 votes vote down vote up
public FlashHandler(CameraManager cameraManager) {
    mCameraManager = cameraManager;

    try {
        for (String camId : mCameraManager.getCameraIdList()) {
            CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(camId);
            Boolean hasFlash = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);

            if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK
                    && Boolean.TRUE.equals(hasFlash)) {
                torchId = camId;
                break;
            }
        }

        if (torchId != null) {
            controller = new FlashControlThread();
            controller.start();
        }
    } catch (CameraAccessException e) {
        Log.d(TAG, "Could not create flash controller");
    }
}
 
Example #22
Source File: CameraActivity.java    From CameraDemo with Apache License 2.0 6 votes vote down vote up
/**
 * 拍照
 */
@SuppressLint("NewApi")
private void takePicture() {
    if (mCameraDevice == null) return;
    // 创建拍照需要的CaptureRequest.Builder
    final CaptureRequest.Builder captureRequestBuilder;
    try {
        captureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        // 将imageReader的surface作为CaptureRequest.Builder的目标
        captureRequestBuilder.addTarget(mImageReader.getSurface());
        // 自动对焦
        captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
        // 自动曝光
        captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        // 获取手机方向
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        // 根据设备方向计算设置照片的方向
        captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(rotation));
        //拍照
        CaptureRequest mCaptureRequest = captureRequestBuilder.build();
        mCameraCaptureSession.capture(mCaptureRequest, null, childHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
 
Example #23
Source File: Camera2.java    From TikTok with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Starts a capture session for camera preview.</p>
 * <p>This rewrites {@link #mPreviewRequestBuilder}.</p>
 * <p>The result will be continuously processed in {@link #mSessionCallback}.</p>
 */
void startCaptureSession() {
    if (!isCameraOpened() || !mPreview.isReady() || mImageReader == null) {
        return;
    }
    Size previewSize = chooseOptimalSize();
    mPreview.setBufferSize(previewSize.getWidth(), previewSize.getHeight());
    Surface surface = mPreview.getSurface();
    try {
        mPreviewRequestBuilder = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);
        mCamera.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                mSessionCallback, null);
    } catch (CameraAccessException e) {
        throw new RuntimeException("Failed to start camera session");
    }
}
 
Example #24
Source File: CameraFragment.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Lock the focus as the first step for a still image capture.
 */
private void lockFocus() {
    Log.d(TAG, "lockFocus: ");
    try {
        // This is how to tell the camera to lock focus.
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CameraMetadata.CONTROL_AF_TRIGGER_START);
        // Tell #mCaptureCallback to wait for the lock.
        mState = STATE_WAITING_LOCK;
        mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), mCaptureCallback,
                mBackgroundHandler);
    } catch (CameraAccessException e) {
        Log.e(TAG, "CameraAccessException: " + e);
        e.printStackTrace();
    }
}
 
Example #25
Source File: Camera2Fragment.java    From Camera2-Video with Apache License 2.0 5 votes vote down vote up
private void startPreview() {
    if (mCameraDevice == null || !mCameraLayout.isAvailable() || mPreviewSize == null) {
        return;
    }
    try {
        setUpMediaRecorder();
        mCameraDevice.createCaptureSession(getSurfaces(), mSessionCallback, mBackgroundHandler);
    } catch (CameraAccessException cae) {
        cae.printStackTrace();
        mCamera2Listener.onCameraException(cae);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        mCamera2Listener.onIOException(ioe);
    }
}
 
Example #26
Source File: Camera2BasicFragment.java    From Android-Camera2-Front-with-Face-Detection with Apache License 2.0 5 votes vote down vote up
/**
 * Lock the focus as the first step for a still image capture.
 */
private void lockFocus() {
    try {
        // This is how to tell the camera to lock focus.
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CameraMetadata.CONTROL_AF_TRIGGER_START);
        // Tell #mCaptureCallback to wait for the lock.
        mState = STATE_WAITING_LOCK;
        mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
 
Example #27
Source File: CameraHandler.java    From sample-tensorflow-imageclassifier with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
@SuppressLint("MissingPermission")
public void initializeCamera(Context context, Handler backgroundHandler, Size minSize,
                             ImageReader.OnImageAvailableListener imageAvailableListener)
    throws CameraAccessException {
    if (initialized) {
        throw new IllegalStateException(
                "CameraHandler is already initialized or is initializing");
    }
    initialized = true;
    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    String camId = getCameraId(context);

    // Initialize the image processor with the largest available size.
    CameraCharacteristics characteristics = manager.getCameraCharacteristics(camId);
    StreamConfigurationMap map = characteristics.get(
        CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

    Size bestSize = getBestCameraSize(map.getOutputSizes(ImageFormat.JPEG), minSize);
    if (bestSize == null) {
        throw new RuntimeException("We could not find a camera resolution that is larger than "
                + minSize.getWidth() + "x" + minSize.getHeight());
    }

    mImageReader = ImageReader.newInstance(bestSize.getWidth(), bestSize.getHeight(),
        ImageFormat.JPEG, MAX_IMAGES);
    mImageDimensions = bestSize;
    Log.d(TAG, "Will capture photos that are " + mImageDimensions.getWidth() + " x " +
        mImageDimensions.getHeight());
    mImageReader.setOnImageAvailableListener(imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(camId, mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.e(TAG, "Camera access exception", cae);
    }
}
 
Example #28
Source File: Camera2BasicFragment.java    From android-Camera2Basic with Apache License 2.0 5 votes vote down vote up
/**
 * Lock the focus as the first step for a still image capture.
 */
private void lockFocus() {
    try {
        // This is how to tell the camera to lock focus.
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                CameraMetadata.CONTROL_AF_TRIGGER_START);
        // Tell #mCaptureCallback to wait for the lock.
        mState = STATE_WAITING_LOCK;
        mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                mBackgroundHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
 
Example #29
Source File: DoorbellCamera.java    From androidthings-cameraCar with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
public void initializeCamera(Context context,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
    String[] camIds = {};
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.d(TAG, "Cam access exception getting IDs", e);
    }
    if (camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    String id = camIds[0];
    Log.d(TAG, "Using camera id " + id);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
            ImageFormat.JPEG, MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(
            imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(id, mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example #30
Source File: MainActivity.java    From AndroidPlayground with MIT License 5 votes vote down vote up
private void initCameraIds() throws CameraAccessException {
    for (String cameraId : mCameraManager.getCameraIdList()) {
        CameraCharacteristics characteristics =
                mCameraManager.getCameraCharacteristics(cameraId);

        Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
        if (facing != null) {
            if (facing == CameraCharacteristics.LENS_FACING_BACK) {
                mBackCameraId = cameraId;
            }
        }
    }
}