notBigEnough = new ArrayList<>();
494 | int w = aspectRatio.getWidth();
495 | int h = aspectRatio.getHeight();
496 | for (Size option : choices) {
497 | if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
498 | option.getHeight() == option.getWidth() * h / w) {
499 | if (option.getWidth() >= textureViewWidth &&
500 | option.getHeight() >= textureViewHeight) {
501 | bigEnough.add(option);
502 | } else {
503 | notBigEnough.add(option);
504 | }
505 | }
506 | }
507 |
508 | // 挑那些最小中的足够大的。如果没有足够大的,选择最大的那些不够大的。
509 | if (bigEnough.size() > 0) {
510 | return Collections.min(bigEnough, new CompareSizesByArea());
511 | } else if (notBigEnough.size() > 0) {
512 | return Collections.max(notBigEnough, new CompareSizesByArea());
513 | } else {
514 | Log.e(TAG, "Couldn't find any suitable preview size");
515 | return choices[0];
516 | }
517 | }
518 |
519 |
520 | /**
521 | * 设置与摄像机相关的成员变量。
522 | *
523 | * @param width 相机预览可用尺寸的宽度
524 | * @param height 相机预览可用尺寸的高度
525 | */
526 | @SuppressWarnings("SuspiciousNameCombination")
527 | private void setUpCameraOutputs(int width, int height) {
528 | CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
529 | try {
530 | String[] cameraIdList = manager.getCameraIdList();
531 | mCameraCount = cameraIdList.length;
532 | for (String cameraId : cameraIdList) {
533 | CameraCharacteristics characteristics
534 | = manager.getCameraCharacteristics(cameraId);
535 |
536 | //判断当前摄像头是前置还是后置摄像头
537 | Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
538 | if (facing != null && facing != mCurrentCameraFacing) {
539 | continue;
540 | }
541 |
542 | StreamConfigurationMap map = characteristics.get(
543 | CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
544 | if (map == null) {
545 | continue;
546 | }
547 |
548 | // 对于静态图像捕获,我们使用最大可用的大小。
549 | Size largest = Collections.max(
550 | Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
551 | new CompareSizesByArea());
552 | mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
553 | ImageFormat.JPEG, /*maxImages*/2);
554 | mImageReader.setOnImageAvailableListener(
555 | mOnImageAvailableListener, mBackgroundHandler);
556 |
557 | // 找出是否需要交换尺寸以获得相对与传感器坐标的预览大小
558 | int displayRotation = mWindowManager.getDefaultDisplay().getRotation();
559 | //检验条件
560 | mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
561 | boolean swappedDimensions = false;
562 | switch (displayRotation) {
563 | case Surface.ROTATION_0:
564 | case Surface.ROTATION_180:
565 | if (mSensorOrientation == 90 || mSensorOrientation == 270) {
566 | swappedDimensions = true;
567 | }
568 | break;
569 | case Surface.ROTATION_90:
570 | case Surface.ROTATION_270:
571 | if (mSensorOrientation == 0 || mSensorOrientation == 180) {
572 | swappedDimensions = true;
573 | }
574 | break;
575 | default:
576 | Log.e(TAG, "Display rotation is invalid: " + displayRotation);
577 | }
578 |
579 | Point displaySize = new Point();
580 | mWindowManager.getDefaultDisplay().getSize(displaySize);
581 | int rotatedPreviewWidth = width;
582 | int rotatedPreviewHeight = height;
583 | int maxPreviewWidth = displaySize.x;
584 | int maxPreviewHeight = displaySize.y;
585 |
586 | if (swappedDimensions) {
587 | rotatedPreviewWidth = height;
588 | rotatedPreviewHeight = width;
589 | maxPreviewWidth = displaySize.y;
590 | maxPreviewHeight = displaySize.x;
591 | }
592 |
593 | if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
594 | maxPreviewWidth = MAX_PREVIEW_WIDTH;
595 | }
596 |
597 | if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
598 | maxPreviewHeight = MAX_PREVIEW_HEIGHT;
599 | }
600 |
601 | // 危险,W.R.!尝试使用太大的预览大小可能超过相机总线的带宽限制,导致高清的预览,但存储垃圾捕获数据。
602 | mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
603 | rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
604 | maxPreviewHeight, largest);
605 |
606 | // 我们将TextureView的宽高比与我们选择的预览大小相匹配。
607 | int orientation = getResources().getConfiguration().orientation;
608 | if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
609 | setAspectRatio(
610 | mPreviewSize.getWidth(), mPreviewSize.getHeight());
611 | } else {
612 | setAspectRatio(
613 | mPreviewSize.getHeight(), mPreviewSize.getWidth());
614 | }
615 |
616 | //检验是否支持flash
617 | Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
618 | mFlashSupported = available == null ? false : available;
619 |
620 | mCameraId = cameraId;
621 | return;
622 | }
623 | } catch (CameraAccessException e) {
624 | e.printStackTrace();
625 | } catch (NullPointerException e) {
626 | //抛出空指针一般代表当前设备不支持Camera2API
627 | Log.e(TAG, "This device doesn't support Camera2 API.");
628 |
629 | }
630 | }
631 |
632 | /**
633 | * 打开指定的相机(mCameraId)
634 | */
635 | private void openCamera(int width, int height) {
636 |
637 | setUpCameraOutputs(width, height);
638 | configureTransform(width, height);
639 |
640 | CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
641 | try {
642 | if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
643 | throw new RuntimeException("Time out waiting to lock camera1 opening.");
644 | }
645 | if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
646 | return;
647 | }
648 | manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
649 | } catch (CameraAccessException e) {
650 | e.printStackTrace();
651 | } catch (InterruptedException e) {
652 | throw new RuntimeException("Interrupted while trying to lock camera1 opening.", e);
653 | }
654 | }
655 |
656 | /**
657 | * 关闭相机
658 | */
659 | private void closeCamera() {
660 | try {
661 | mCameraOpenCloseLock.acquire();
662 | if (null != mCaptureSession) {
663 | mCaptureSession.close();
664 | mCaptureSession = null;
665 | }
666 | if (null != mCameraDevice) {
667 | mCameraDevice.close();
668 | mCameraDevice = null;
669 | }
670 | if (null != mImageReader) {
671 | mImageReader.close();
672 | mImageReader = null;
673 | }
674 | } catch (InterruptedException e) {
675 | throw new RuntimeException("Interrupted while trying to lock camera1 closing.", e);
676 | } finally {
677 | mCameraOpenCloseLock.release();
678 | }
679 | }
680 |
681 | /**
682 | * 启动后台线程和Handler.
683 | */
684 | private void startBackgroundThread() {
685 | mBackgroundThread = new HandlerThread("CameraBackground");
686 | mBackgroundThread.start();
687 | mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
688 | }
689 |
690 | /**
691 | * 停止后台线程和Handler.
692 | */
693 | private void stopBackgroundThread() {
694 | mBackgroundThread.quitSafely();
695 | try {
696 | mBackgroundThread.join();
697 | mBackgroundThread = null;
698 | mBackgroundHandler = null;
699 | } catch (InterruptedException e) {
700 | e.printStackTrace();
701 | }
702 | }
703 |
704 | /**
705 | * 创建一个新的 {@link CameraCaptureSession} 用于相机预览.
706 | */
707 | private void createCameraPreviewSession() {
708 | try {
709 | SurfaceTexture texture = getSurfaceTexture();
710 | assert texture != null;
711 |
712 | // 我们将默认缓冲区的大小设置为我们想要的相机预览的大小。
713 | texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
714 |
715 | // 我们需要开始预览输出Surface
716 | Surface surface = new Surface(texture);
717 |
718 | // 我们建立了一个具有输出Surface的捕获器。
719 | mPreviewRequestBuilder
720 | = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
721 | mPreviewRequestBuilder.addTarget(surface);
722 |
723 | // 这里,我们创建了一个用于相机预览的CameraCaptureSession
724 | mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
725 | new CameraCaptureSession.StateCallback() {
726 |
727 | @Override
728 | public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
729 | // 相机已经关闭
730 | if (null == mCameraDevice) {
731 | return;
732 | }
733 |
734 | // 当session准备好后,我们开始显示预览
735 | mCaptureSession = cameraCaptureSession;
736 | try {
737 | // 相机预览时应连续自动对焦
738 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
739 | CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
740 | // 设置闪光灯在必要时自动打开
741 | setAutoFlash(mPreviewRequestBuilder);
742 |
743 | // 最终,显示相机预览
744 | mPreviewRequest = mPreviewRequestBuilder.build();
745 | mCaptureSession.setRepeatingRequest(mPreviewRequest,
746 | mCaptureCallback, mBackgroundHandler);
747 | } catch (CameraAccessException e) {
748 | e.printStackTrace();
749 | }
750 | }
751 |
752 | @Override
753 | public void onConfigureFailed(
754 | @NonNull CameraCaptureSession cameraCaptureSession) {
755 | Log.e(TAG, "CameraCaptureSession.StateCallback onConfigureFailed");
756 | }
757 | }, null
758 | );
759 | } catch (CameraAccessException e) {
760 | e.printStackTrace();
761 | }
762 | }
763 |
764 | /**
765 | * 配置必要的 {@link android.graphics.Matrix} 转换为 `mTextureView`.
766 | *
767 | * 该方法应该在setUpCameraOutputs中确定相机预览大小以及“mTextureView”的大小固定之后调用。
768 | *
769 | * @param viewWidth The width of `mTextureView`
770 | * @param viewHeight The height of `mTextureView`
771 | */
772 | private void configureTransform(int viewWidth, int viewHeight) {
773 | if (null == mPreviewSize || null == mContext) {
774 | return;
775 | }
776 |
777 | int rotation = mWindowManager.getDefaultDisplay().getRotation();
778 | Matrix matrix = new Matrix();
779 | RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
780 | RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
781 | float centerX = viewRect.centerX();
782 | float centerY = viewRect.centerY();
783 | if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
784 | bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
785 | matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
786 | float scale = Math.max(
787 | (float) viewHeight / mPreviewSize.getHeight(),
788 | (float) viewWidth / mPreviewSize.getWidth());
789 | matrix.postScale(scale, scale, centerX, centerY);
790 | matrix.postRotate(90 * (rotation - 2), centerX, centerY);
791 | } else if (Surface.ROTATION_180 == rotation) {
792 | matrix.postRotate(180, centerX, centerY);
793 | }
794 | setTransform(matrix);
795 | }
796 |
797 |
798 | /**
799 | * 锁定焦点作为静态图像捕获的第一步
800 | */
801 | private void lockFocus() {
802 | try {
803 | // 这里是让相机锁定焦点
804 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
805 | CameraMetadata.CONTROL_AF_TRIGGER_START);
806 | // 告知 #mCaptureCallback 等待锁
807 | mState = STATE_WAITING_LOCK;
808 | mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
809 | mBackgroundHandler);
810 | } catch (CameraAccessException e) {
811 | e.printStackTrace();
812 | }
813 | }
814 |
815 | /**
816 | * 运行预捕获序列捕获一张静态图片。
817 | *
818 | * 这个方法应该在我们从得到mCaptureCallback的响应后调用
819 | */
820 | private void runPrecaptureSequence() {
821 | try {
822 | // 这就是如何告诉相机触发。
823 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
824 | CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
825 | // 告知 #mCaptureCallback 等待设置预捕获序列。
826 | mState = STATE_WAITING_PRECAPTURE;
827 | mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
828 | mBackgroundHandler);
829 | } catch (CameraAccessException e) {
830 | e.printStackTrace();
831 | }
832 | }
833 |
834 | /**
835 | * 捕获一张静态图片
836 | * 这个方法应该在我们从得到mCaptureCallback的响应后调用
837 | */
838 | private void captureStillPicture() {
839 | try {
840 | if (null == mCameraDevice) {
841 | return;
842 | }
843 | // 这是 CaptureRequest.Builder ,我们用它来进行拍照
844 | final CaptureRequest.Builder captureBuilder =
845 | mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
846 | captureBuilder.addTarget(mImageReader.getSurface());
847 |
848 | // 使用相同的AE和AF模式作为预览。
849 | captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
850 | CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
851 | setAutoFlash(captureBuilder);
852 |
853 | // 方向
854 | int rotation = mWindowManager.getDefaultDisplay().getRotation();
855 | captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));
856 |
857 | CameraCaptureSession.CaptureCallback CaptureCallback
858 | = new CameraCaptureSession.CaptureCallback() {
859 |
860 | @Override
861 | public void onCaptureCompleted(@NonNull CameraCaptureSession session,
862 | @NonNull CaptureRequest request,
863 | @NonNull TotalCaptureResult result) {
864 | Log.d(TAG, "CameraCaptureSession.CaptureCallback onCaptureCompleted 图片保存地址为:" + mPictureFile.toString());
865 | if (mTakePictureCallback != null) {
866 | mTakePictureCallback.success(mPictureFile.getAbsolutePath());
867 | }
868 | unlockFocus();
869 | }
870 | };
871 |
872 | mCaptureSession.stopRepeating();
873 | mCaptureSession.abortCaptures();
874 | mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
875 | } catch (CameraAccessException e) {
876 | e.printStackTrace();
877 | }
878 | }
879 |
880 | /**
881 | * 从指定的屏幕旋转中检索JPEG方向。
882 | *
883 | * @param rotation 图片旋转
884 | * @return The JPEG orientation (one of 0, 90, 270, and 360)
885 | */
886 | private int getOrientation(int rotation) {
887 | // 对于大多数设备,传感器定向是90,对于某些设备(例如Nexus 5X)是270。
888 | //我们必须考虑到这一点,并适当的旋转JPEG。
889 | //对于取向为90的设备,我们只需从方向返回映射即可。
890 | //对于方向为270的设备,我们需要旋转JPEG 180度。
891 | return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
892 | }
893 |
894 | /**
895 | * 解锁焦点.
896 | *
897 | * 此方法应该在静态图片捕获序列结束后调用
898 | */
899 | private void unlockFocus() {
900 | try {
901 | // 重置自动对焦触发
902 | mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
903 | CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
904 | setAutoFlash(mPreviewRequestBuilder);
905 | mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
906 | mBackgroundHandler);
907 | // 在此之后,相机将回到正常的预览状态。
908 | mState = STATE_PREVIEW;
909 | mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
910 | mBackgroundHandler);
911 | } catch (CameraAccessException e) {
912 | e.printStackTrace();
913 | }
914 | }
915 |
916 |
917 | private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
918 | if (mFlashSupported) {
919 | requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
920 | CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
921 | }
922 | }
923 |
924 | /**
925 | * 将JPEG{@link Image}保存并放到指定的文件中
926 | */
927 | private static class ImageSaver implements Runnable {
928 |
929 | /**
930 | * The JPEG image
931 | */
932 | private final Image mImage;
933 | /**
934 | * The file we save the image into.
935 | */
936 | private final File mFile;
937 |
938 | ImageSaver(Image image, File file) {
939 | mImage = image;
940 | mFile = file;
941 | }
942 |
943 | @Override
944 | public void run() {
945 | ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
946 | byte[] bytes = new byte[buffer.remaining()];
947 | buffer.get(bytes);
948 | FileOutputStream output = null;
949 | try {
950 | output = new FileOutputStream(mFile);
951 | output.write(bytes);
952 | } catch (IOException e) {
953 | e.printStackTrace();
954 | } finally {
955 | mImage.close();
956 | if (null != output) {
957 | try {
958 | output.close();
959 | } catch (IOException e) {
960 | e.printStackTrace();
961 | }
962 | }
963 | }
964 | }
965 |
966 | }
967 |
968 | /**
969 | * 根据它们的区域比较两个的大小 {@code Size}。
970 | */
971 | static class CompareSizesByArea implements Comparator {
972 |
973 | @Override
974 | public int compare(Size lhs, Size rhs) {
975 | // We cast here to ensure the multiplications won't overflow
976 | return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
977 | (long) rhs.getWidth() * rhs.getHeight());
978 | }
979 |
980 | }
981 |
982 |
983 | }
984 |
--------------------------------------------------------------------------------