• Android相机调用-CameraX【外接摄像头】【USB摄像头】


    Android相机调用有原生的Camera和Camera2,我觉得调用代码都太复杂了,CameraX调用代码简洁很多。

    说明文档:https://developer.android.com/jetpack/androidx/releases/camera?hl=zh-cn

    现有查到的调用资料都不够新,对于外接摄像头(USB摄像头)这类非前置也非后置摄像头的设备调用,都说是没有实现。旧版本的库可能更多目标用户是基于手机的,1.3.0-alpha03版本针对外接摄像头有增加配置项(CameraSelector.LENS_FACING_EXTERNAL),使用该配置项可以实现外接摄像头的调用。

    0,摄像头选择可用值

    1. /** A camera on the devices that its lens facing is resolved. */
    2. public static final int LENS_FACING_UNKNOWN = -1;
    3. /** A camera on the device facing the same direction as the device's screen. */
    4. public static final int LENS_FACING_FRONT = 0;
    5. /** A camera on the device facing the opposite direction as the device's screen. */
    6. public static final int LENS_FACING_BACK = 1;
    7. /**
    8. * An external camera that has no fixed facing relative to the device's screen.
    9. *
    10. *

      The behavior of an external camera highly depends on the manufacturer. Currently it's

    11. * treated similar to a front facing camera with little verification. So it's considered
    12. * experimental and should be used with caution.
    13. */
    14. @ExperimentalLensFacing
    15. public static final int LENS_FACING_EXTERNAL = 2;

    1,在AndroidManifest.xml添加权限

    1. <uses-permission android:name="android.permission.CAMERA" />
    2. <uses-feature android:name="android.hardware.camera.any" />

    2,在settings.gradle或build.gradle添加maven

    1. repositories {
    2. google()
    3. mavenCentral()
    4. maven { url 'https://jitpack.io' }
    5. }

    3,在build.gradle添加依赖库

    1. //摄像头预览库
    2. implementation "androidx.camera:camera-core:1.3.0-alpha04"
    3. // CameraX Camera2 extensions[可选]拓展库可实现人像、HDR、夜间和美颜、滤镜但依赖于OEM
    4. implementation "androidx.camera:camera-camera2:1.3.0-alpha04"
    5. // CameraX Lifecycle library[可选]避免手动在生命周期释放和销毁数据
    6. implementation "androidx.camera:camera-lifecycle:1.3.0-alpha04"
    7. // CameraX View class[可选]最佳实践,最好用里面的PreviewView,它会自行判断用SurfaceView还是TextureView来实现
    8. implementation 'androidx.camera:camera-view:1.3.0-alpha04'

    4,开启预览代码

    1. private ListenableFuture cameraProviderFuture;
    2. private PreviewView previewView;
    3. private ProcessCameraProvider cameraProvider;
    4. ImageView picture = null;
    5. @Override
    6. protected void onCreate(Bundle savedInstanceState) {
    7. super.onCreate(savedInstanceState);
    8. setContentView(R.layout.activity_main);
    9. picture = (ImageView) findViewById(R.id.picture);
    10. previewView=findViewById(R.id.previewView);//初始化
    11. //高版本系统动态权限申请
    12. if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
    13. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    14. requestPermissions(new String[]{
    15. Manifest.permission.CAMERA,
    16. }, 11);
    17. }
    18. } else {
    19. //启动相机
    20. startCamera();
    21. }
    22. takePhoto.setOnClickListener(new View.OnClickListener() {
    23. @Override
    24. public void onClick(View view) {
    25. takePhoto(picture);//取图识别
    26. }
    27. });
    28. }
    29. @Override
    30. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    31. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    32. if (requestCode==11){//获取权限后,开启摄像头
    33. //启动相机
    34. startCamera();
    35. }
    36. }
    37. private void startCamera() {
    38. // 请求 CameraProvider
    39. cameraProviderFuture = ProcessCameraProvider.getInstance(this);
    40. //检查 CameraProvider 可用性,验证它能否在视图创建后成功初始化
    41. cameraProviderFuture.addListener(() -> {
    42. try {
    43. ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
    44. bindPreview(cameraProvider);
    45. } catch (ExecutionException | InterruptedException e) {
    46. // No errors need to be handled for this Future.
    47. // This should never be reached.
    48. }
    49. }, ContextCompat.getMainExecutor(this));
    50. }
    51. //选择相机并绑定生命周期和用例
    52. private void bindPreview(@NonNull ProcessCameraProvider cp) {
    53. this.cameraProvider=cp;
    54. Preview preview = new Preview.Builder()
    55. .build();
    56. @SuppressLint("UnsafeOptInUsageError")
    57. CameraSelector cameraSelector = new CameraSelector.Builder()
    58. .requireLensFacing(CameraSelector.LENS_FACING_BACK)//CameraSelector.LENS_FACING_EXTERNAL
    59. .build();
    60. preview.setSurfaceProvider(previewView.getSurfaceProvider());
    61. cameraProvider.unbindAll();//解绑组件
    62. cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview);
    63. }
    64. //拍照,这里偷懒了,直接取了预览控件的图片,需要拍照的再去看看官方文档吧
    65. public void takePhoto(View view)
    66. {
    67. Log.e("OCR", "takePhoto");
    68. Bitmap bitmap = previewView.getBitmap();
    69. view.setBackground(new BitmapDrawable(getApplicationContext().getResources(),bitmap)); //show picture
    70. }
    71. @Override
    72. protected void onDestroy() {
    73. super.onDestroy();
    74. cameraProvider.unbindAll();
    75. }

    5,界面布局

    1. "1.0" encoding="utf-8"?>
    2. "http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:layout_width="match_parent"
    6. android:layout_height="match_parent"
    7. tools:context=".MainActivity">
    8. android:layout_width="match_parent"
    9. android:layout_height="wrap_content"
    10. android:layout_margin="5dp"
    11. android:orientation="vertical">
    12. android:id="@+id/previewView"
    13. android:layout_width="300dp"
    14. android:layout_height="300dp"
    15. android:layout_gravity="center"
    16. />
    17. android:id="@+id/take_photo"
    18. android:layout_width="match_parent"
    19. android:layout_height="wrap_content"
    20. android:layout_margin="5dp"
    21. android:text="取图"/>
    22. android:id="@+id/picture"
    23. android:layout_width="300dp"
    24. android:layout_height="300dp"
    25. android:layout_gravity="center"
    26. />

    6,测试效果(文字识别部分请忽略)

    s

    7,库的调用版本是比较新的,建议JDK版本不要太低,我使用的是16.0.2

    本方案无法预览的系统请参考libusbcamera博文:Android相机调用-libusbCamera【外接摄像头】【USB摄像头】 【多摄像头预览】-CSDN博客

    新人入行,经验分享,如有所误,欢迎指出~

    版权归属:深圳市琪智科技有限公司-花花

  • 相关阅读:
    APS高级排程实现食品制造企业的智能化排产
    GC0053-STM32单片机NTC热敏电阻温度采集及控制LCD1602
    C++菜鸟日记2
    音视频PTS、DTS
    Spring Boot 自动配置
    对比编程语言的四种错误处理方法,哪种才是最优方案?
    圆桌式开发是什么?如何实现?
    javaWeb环境搭建LInux
    gradle尚硅谷笔记
    MultiBank Group宣布在阿联酋和新加坡取得两项新牌照
  • 原文地址:https://blog.csdn.net/lsh670660992/article/details/132738080