@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 } } } }
void setManualFocusAt(int x, int y) { int mDisplayOrientation = getActivity().getWindowManager().getDefaultDisplay().getRotation(); float points[] = new float[2]; points[0] = (float) x / mTextureView.getWidth(); points[1] = (float) y / mTextureView.getHeight(); Matrix rotationMatrix = new Matrix(); rotationMatrix.setRotate(mDisplayOrientation, 0.5f, 0.5f); rotationMatrix.mapPoints(points); if (mPreviewRequestBuilder != null) { mIsManualFocusing = true; updateManualFocus(points[0], points[1]); if (mPreviewSession != null) { try { mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START); mPreviewSession.capture(mPreviewRequestBuilder.build(), null, mBackgroundHandler); mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE); mPreviewSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler); } catch (CameraAccessException | IllegalStateException e) { Log.e(TAG, "Failed to set manual focus.", e); } } resumeAutoFocusAfterManualFocus(); } }
/** * Unlock the focus. This method should be called when still image capture sequence is * finished. */ private void unlockFocus() { try { // Reset the auto-focus trigger mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL); setAutoFlash(mPreviewRequestBuilder); mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler); // After this, the camera will go back to the normal state of preview. mState = STATE_PREVIEW; mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
@Override public void onOpened(CameraDevice camera) { checkIsOnCameraThread(); Logging.d(TAG, "Camera opened."); cameraDevice = camera; final SurfaceTexture surfaceTexture = surfaceTextureHelper.getSurfaceTexture(); surfaceTexture.setDefaultBufferSize(captureFormat.width, captureFormat.height); surface = new Surface(surfaceTexture); List<Surface> surfaces = new ArrayList<Surface>(); surfaces.add(surface); if (mediaRecorderSurface != null) { Logging.d(TAG, "Add MediaRecorder surface to capture session."); surfaces.add(mediaRecorderSurface); } try { camera.createCaptureSession(surfaces, new CaptureSessionCallback(), cameraThreadHandler); } catch (CameraAccessException e) { reportError("Failed to create capture session. " + e); return; } }
/** * Unlock the focus. This method should be called when still image capture sequence is * finished. */ private void unlockFocus() { try { // Reset the auto-focus trigger mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL); mPreviewSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler); updateAutoFocus(); updateFlash(mPreviewRequestBuilder); // After this, the camera will go back to the normal state of preview. mState = STATE_PREVIEW; mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE); mPreviewSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
private boolean setupCameraIfNeeded() { if (cameraId != null) { return true; } try { cameraId = cameraManager.getCameraIdList()[0]; // Usually back camera is at 0 position } catch (CameraAccessException e) { Log.v(TAG, "failed to set up camera"); return false; } torchEnabled = false; Handler handler = new Handler(); torchCallback = new CameraManager.TorchCallback() { @Override public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) { super.onTorchModeChanged(cameraId, enabled); torchEnabled = enabled; } }; cameraManager.registerTorchCallback(torchCallback, handler); Log.v(TAG, "registered torch callback"); return true; }
@Override 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 } } } }
/** * <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"); } }
/** * 相机开启 * @param width TextureView的宽度 * @param height TextureView的高度 */ private void openCamera(int width, int height) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // requestCameraPermission(); return; } setUpCameraOutputs(width, height); configureTransform(width, height); try { cameraManager.openCamera(cameraID, deviceStateCallback, mainHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
/** * Unlocks the auto-focus and restart camera preview. This is supposed to be called after * capturing a still picture. */ void unlockFocus() { mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_CANCEL); try { mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, null); updateAutoFocus(); updateFlash(); mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE); mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), mCaptureCallback, null); mCaptureCallback.setState(PictureCaptureCallback.STATE_PREVIEW); } catch (CameraAccessException e) { Log.e(TAG, "Failed to restart camera preview.", e); } }
private void openCamera(String cameraId) { try { // CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId); // characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); if (ActivityCompat.checkSelfPermission(getContext(), permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } setUpCameraOutputs(cameraId, ttv_camera.getWidth(), ttv_camera.getHeight()); configureTransform(ttv_camera.getWidth(), ttv_camera.getHeight()); mCameraManager.openCamera(cameraId, mCameraDeviceStateCallback, mHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
/** * Set a repeating burst request. */ public void setRepeatingBurst(final List<CaptureRequest> requests, final CameraCaptureSession.CaptureCallback listener, final Handler handler) { mCameraHandler.post(() -> { try { mCameraSession.setRepeatingBurst(requests, listener, handler); } catch (CameraAccessException e) { String errorMessage = mErrorDisplayer.getErrorString(e); mErrorDisplayer.showErrorDialog(errorMessage); } }); }
private void start() { checkIsOnCameraThread(); Logging.d(TAG, "start"); try { cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId); } catch (final CameraAccessException e) { reportError("getCameraCharacteristics(): " + e.getMessage()); return; } cameraOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); isCameraFrontFacing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraMetadata.LENS_FACING_FRONT; findCaptureFormat(); openCamera(); }
/** * Begin a still image capture */ public void takePicture() { if (mCameraDevice == null) { Log.w(TAG, "Cannot capture image. Camera not initialized."); return; } // Here, we create a CameraCaptureSession for capturing still images. try { mCameraDevice.createCaptureSession( Collections.singletonList(mImageReader.getSurface()), mSessionCallback, null); } catch (CameraAccessException cae) { Log.d(TAG, "access exception while preparing pic", cae); } }
public void setFlashlight(boolean enabled) { boolean pendingError = false; synchronized (this) { if (mFlashlightEnabled != enabled) { mFlashlightEnabled = enabled; try { mCameraManager.setTorchMode(mCameraId, enabled); } catch (CameraAccessException e) { Log.e(TAG, "Couldn't set torch mode", e); mFlashlightEnabled = false; pendingError = true; } } } dispatchModeChanged(mFlashlightEnabled); if (pendingError) { dispatchError(); } }
/** * Unlock the focus. This method should be called when still image capture sequence is * finished. */ private void unlockFocus() { try { // Reset the auto-focus trigger mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL); if(mFlashSupported) { mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, mFlashMode); } mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler); // After this, the camera will go back to the normal state of preview. mState = STATE_PREVIEW; mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
@Override protected String createCamera(int deviceDegrees) throws CameraException { try { for (String camId : mCamManager.getCameraIdList()) { CameraCharacteristics characteristics = mCamManager.getCameraCharacteristics(camId); Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); if (facing == CameraCharacteristics.LENS_FACING_FRONT) { Log.d(TAG, "front-facing mCamera found: " + camId); return camId; } } } catch (CameraAccessException e) { throw new CameraException(e); } throw new CameraException(mActivity.getString(R.string.frontCameraMissing)); }
@Override protected String getCameraInfo() { String camStr = mContext.getString(R.string.camApi2) + "\n"; CameraManager camManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE); try { for (String camId : camManager.getCameraIdList()) { camStr += mContext.getString(R.string.cameraId, camId) + ": "; CameraCharacteristics characteristics = camManager.getCameraCharacteristics(camId); Boolean hasFlash = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING); camStr += (hasFlash ? mContext.getString(R.string.has) : mContext.getString(R.string.no)) + " " + mContext.getString(R.string.flash) + ", "; camStr += (facing == CameraCharacteristics.LENS_FACING_BACK ? mContext.getString(R.string.backFacing) : mContext.getString(R.string.frontFacing)) + "\n"; } } catch (CameraAccessException e) { camStr = mActivity.getString(R.string.failedAccessCamera) + ":" + e.getMessage(); } return camStr.trim(); }
private void doPreviewConfiguration() { if (mCamera == null) { return; } try { // mPreviewBuilder = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); // mPreviewBuilder.addTarget(surfaceView.getHolder().getSurface()); // mPreviewBuilder.addTarget(mImageReader.getSurface()); mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO); // mPreviewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO); // mPreviewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF); // mPreviewBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF); mPreviewBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, mFps[mFps.length -1 ]); mCaptureSession.setRepeatingRequest(mPreviewBuilder.build(), mPreCaptureCallback, mHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
@Override public void collectRatioSizes() { ratioSizeList.clear(); CameraCharacteristics characteristics; StreamConfigurationMap map = null; try { characteristics = ((CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE)).getCameraCharacteristics(Integer.toString(Integer.parseInt(getCameraId()))); map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); } catch (CameraAccessException e) { e.printStackTrace(); } Size[] outputSizes = map.getOutputSizes(SurfaceTexture.class); if (outputSizes != null) { List<Double> ratioList = new ArrayList<>(); for (Size size : outputSizes) { double ratio = (double) size.getWidth() / (double) size.getHeight(); if (!ratioList.contains(ratio)) { ratioList.add(ratio); ratioSizeList.add(new AspectRatio(ratio, size.getWidth(), size.getHeight())); } } } }
/** * Called after a RAW/JPEG capture has completed; resets the AF trigger state for the * pre-capture sequence. * <p/> * Call this only with {@link #mCameraStateLock} held. */ private void finishedCaptureLocked() { try { // Reset the auto-focus trigger in case AF didn't run quickly enough. if (!mNoAFRun) { mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL); mCaptureSession.capture(mPreviewRequestBuilder.build(), mPreCaptureCallback, mBackgroundHandler); mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_IDLE); } } catch (CameraAccessException e) { e.printStackTrace(); } }
@NonNull private <T> T getOrThrow(@NonNull String cameraId, @NonNull CameraCharacteristics.Key<T> key) { try { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId); T value = characteristics.get(key); if (value == null) { throw new CameraException("could not determine camera characteristic " + key.getName() + " from camera " + cameraId); } else { return value; } } catch (CameraAccessException e) { throw new CameraException(e); } }
/** * Does open the front-facing camera of the device. * Make sure to close the camera object which is returned within the callback! * * @param callback set of callback functions which are called when the opening process completed * @throws CameraException if the camera could not be opened */ @RequiresPermission(Manifest.permission.CAMERA) public void openFrontFacingCamera(@NonNull CameraDevice.StateCallback callback) { try { String cameraId = getFrontFacingCameraId(); if (cameraId == null) { throw new CameraException("device is missing a front-facing camera"); } logSupportedHardwareLevel(cameraId); manager.openCamera(cameraId, callback, null); } catch (CameraAccessException e) { throw new CameraException(e); } }
/** * does setup the repeating capture request for taking images for the preview */ @VisibleForTesting void setupCaptureRequestForPreview(@NonNull CameraCaptureSession previewSession, @NonNull CameraDevice camera, @NonNull List<Surface> surfaces) { try { CaptureRequest.Builder previewRequestBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); for (Surface surface : surfaces) { previewRequestBuilder.addTarget(surface); } previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); previewSession.setRepeatingRequest(previewRequestBuilder.build(), null, null); } catch (CameraAccessException | IllegalStateException e) { throw new CameraException(e); } }
/** * Lock the focus as the first step for a still image capture. */ private void lockFocus() { try { Log.d(TAG, "lockFocus: "); // 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(); } }
/** * Run the precapture sequence for capturing a still image. This method should be called when * we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}. */ private void runPrecaptureSequence() { try { // This is how to tell the camera to trigger. mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START); // Tell #mCaptureCallback to wait for the precapture sequence to be set. mState = STATE_WAITING_PRECAPTURE; mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } }
private void initCamera() { cameraID = "" + CameraCharacteristics.LENS_FACING_BACK; cameraManager = (CameraManager) getContext().getSystemService(CAMERA_SERVICE); try { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(getContext(), "请授权使用照相机", Toast.LENGTH_SHORT).show(); return; } //$ process in background cameraManager.openCamera(cameraID, cameraStateCallback, backGroundHandler1); } catch (CameraAccessException e) { e.printStackTrace(); } }
@Override public void startCamera() { try { CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraID); StreamConfigurationMap configMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); int width = textureView.getWidth(); int height = textureView.getHeight(); //设置一个合适的预览尺寸,防止图像拉伸 // previewSize = getPreferredPreviewSize(configMap.getOutputSizes(SurfaceTexture.class), width, height); previewSize = Util.getPreferredPreviewSize(configMap.getOutputSizes(ImageFormat.JPEG), width, height); surfaceTexture.setDefaultBufferSize(previewSize.getWidth(),previewSize.getHeight()); Log.i(TAG, "previewSize info:" + previewSize.getWidth() + "x" + previewSize.getHeight()); surface = new Surface(surfaceTexture); builder =cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); if (surface.isValid()) { builder.addTarget(surface); } Log.i(TAG, "mTextureView info:" + textureView.getWidth() + "x" + textureView.getHeight()); cameraDevice.createCaptureSession(Arrays.asList(surface),sessionStateCallback,null); } catch (CameraAccessException e) { e.printStackTrace(); } }
private void captureStillPicture() { try { if (null == cameraDevice) { return; } final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(imageReader.getSurface()); captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getPhotoOrientation(configurationProvider.getSensorPosition())); CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() { @Override public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) { Log.d(TAG, "onCaptureCompleted: "); } }; captureSession.stopRepeating(); captureSession.capture(captureBuilder.build(), CaptureCallback, null); } catch (CameraAccessException e) { Log.e(TAG, "Error during capturing picture"); } }
/** * <p>Starts opening a camera device.</p> * <p>The result will be processed in {@link #mCameraDeviceCallback}.</p> */ private void startOpeningCamera() { try { mCameraManager.openCamera(mCameraId, mCameraDeviceCallback, null); } catch (CameraAccessException e) { throw new RuntimeException("Failed to open camera: " + mCameraId, e); } }
private void closePreviewSession() { if (mPreviewSession != null) { try { mPreviewSession.stopRepeating(); } catch (CameraAccessException e) { e.printStackTrace(); } mPreviewSession.close(); mPreviewSession = null; } }
@Override public void stopCamera() { try { cameraCaptureSession.abortCaptures(); cameraDevice.close(); } catch (CameraAccessException e) { e.printStackTrace(); } textureView.setVisibility(View.GONE); }
/** * Execute a new capture request within the active session */ private void triggerImageCapture() { try { final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); captureBuilder.addTarget(mImageReader.getSurface()); captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); Log.d(TAG, "Capture request created."); mCaptureSession.capture(captureBuilder.build(), mCaptureCallback, null); } catch (CameraAccessException cae) { Log.d(TAG, "camera capture exception"); } }
/** * 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(); } }
private void switchCamera() { try { mCurrentCameraId = (mCurrentCameraId + 1) % mCameraManager.getCameraIdList().length; releaseCamera(); openCamera(mCurrentCameraId); } catch (CameraAccessException e) { e.printStackTrace(); } }