Android App开发——使用CameraX打开前后摄像头拍照并保存(Java实现)

前言

开发环境是Android studio 北极狐,CameraX1.0.0-alpha02,实现语言是Java。

创建工程

1.引入CameraX
在build.gradle添加要引入CameraX的版本。
在这里插入图片描述

 //CameraX
    def camerax_version = "1.0.0-alpha02"
    implementation "androidx.camera:camera-core:${camerax_version}"
    implementation "androidx.camera:camera-camera2:${camerax_version}"

2.在AndroidManifest.xml添加打开摄像头的权限和读写文件的权限。
在这里插入图片描述

  <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  android:requestLegacyExternalStorage="true"

3.在工程里面新添加一个Activity。
在这里插入图片描述
在这里插入图片描述
4.CameraXDemo代码。

public class IdentificationPhoto extends AppCompatActivity
{
    private int REQUEST_CODE_PERMISSIONS = 101;
    private final String [] REQUIRED_PERMISSIONS =new String[] {"android.permission.CAMERA","android.permission.WRITE_EXTERNAL_STORAGE"};
    TextureView textureView;
    ImageView cameraFlip;
    private int backlensfacing = 0;
    private int flashLamp = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camerax_demo);

        //去掉导航栏
        getSupportActionBar().hide();

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }


        textureView = findViewById(R.id.view_camera);
        cameraFlip = findViewById(R.id.btn_switch_camera);


        cameraFlip.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                if(backlensfacing == 0)
                {
                    startCamera(CameraX.LensFacing.FRONT);
                    backlensfacing = 1;
                }
                else if(backlensfacing == 1)
                {
                    startCamera(CameraX.LensFacing.BACK);
                    backlensfacing = 0;
                }
            }

        });

        if(allPermissionsGranted())
        {
            startCamera(CameraX.LensFacing.BACK);
        }
        else {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
        }


    }


    private void startCamera(CameraX.LensFacing CAMERA_ID)
    {
        unbindAll();
        Rational aspectRatio = new Rational(textureView.getWidth(), textureView.getHeight());
        Size screen = new Size(textureView.getWidth(),textureView.getHeight());
        PreviewConfig pConfig;
        Preview preview;
        pConfig = new PreviewConfig.Builder().setLensFacing(CAMERA_ID).setTargetAspectRatio(aspectRatio).setTargetResolution(screen).build();
        preview = new Preview(pConfig);

        preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
            @Override
            public void onUpdated(Preview.PreviewOutput output)
            {
                ViewGroup parent = (ViewGroup)textureView.getParent();
                parent.removeView(textureView);
                parent.addView(textureView,0);
                textureView.setSurfaceTexture(output.getSurfaceTexture());
                updateTransform();
            }
        });
        final ImageCaptureConfig imageCaptureConfig ;
        imageCaptureConfig= new ImageCaptureConfig.Builder().setCaptureMode(ImageCapture.CaptureMode.MAX_QUALITY).setTargetRotation(getWindowManager().getDefaultDisplay().getRotation()).setLensFacing(CAMERA_ID).build();
        final ImageCapture imgCap = new ImageCapture(imageCaptureConfig);

        findViewById(R.id.btn_flash).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                if (flashLamp == 0)
                {
                    flashLamp = 1;
                    imgCap.setFlashMode(FlashMode.OFF);
                    Toast.makeText(getBaseContext(), "Flash Disable", Toast.LENGTH_SHORT).show();
                }
                else if(flashLamp == 1)
                {
                    flashLamp = 0;
                    imgCap.setFlashMode(FlashMode.ON);
                    Toast.makeText(getBaseContext(), "Flash Enable", Toast.LENGTH_SHORT).show();
                }
            }
        });

        findViewById(R.id.btn_takePict).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                File image = null;
                String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date());
                String imageFileName = "JPEG_"+ timeStamp + "_";
                File storageDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                try {
                    image = File.createTempFile(
                            imageFileName,
                            ".jpeg",
                            storageDir);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                File file = new File(image.getAbsolutePath());
                imgCap.takePicture(file, new ImageCapture.OnImageSavedListener()
                {
                    @Override
                    public void onImageSaved(@NonNull File file)
                    {
                        String msg = "Pic saved at "+ file.getAbsolutePath();
                        galleryAddPic(file.getAbsolutePath());
                        Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onError(@NonNull ImageCapture.UseCaseError useCaseError, @NonNull String message, @Nullable Throwable cause) {
                        String msg = "Pic saved at "+ message;
                        Toast.makeText(getBaseContext(), msg,Toast.LENGTH_LONG).show();
                        if (cause !=null){
                            cause.printStackTrace();

                            Toast.makeText(getBaseContext(), cause.toString(),Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });

        bindToLifecycle(this,preview, imgCap);

    }

    private void galleryAddPic(String  currentFilePath){
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File file = new File (currentFilePath);
        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
        //Toast.makeText(getBaseContext(), "saved to gallery",Toast.LENGTH_LONG).show();
    }

    private void updateTransform(){
        Matrix mx = new Matrix();
        float w = textureView.getMeasuredWidth();
        float h = textureView.getMeasuredHeight();
        float cX = w / 2f;
        float cY = h / 2f;
        int rotationDgr;
        int rotation = (int)textureView.getRotation();
        switch (rotation){
            case Surface.ROTATION_0:
                rotationDgr = 0;
                break;
            case Surface.ROTATION_90:
                rotationDgr = 90;
                break;
            case Surface.ROTATION_180:
                rotationDgr = 180;
                break;
            case Surface.ROTATION_270:
                rotationDgr = 270;
                break;
            default: return;
        }
        mx.postRotate((float)rotationDgr, cX,cY);
        textureView.setTransform(mx);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_CODE_PERMISSIONS){
            if (allPermissionsGranted()) {

                startCamera(CameraX.LensFacing.BACK);
            }
            else{
                Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private boolean allPermissionsGranted()
    {
        for(String permission : REQUIRED_PERMISSIONS)
        {
            if(ContextCompat.checkSelfPermission(this, permission)!= PackageManager.PERMISSION_GRANTED)
            {
                return false;
            }
        }
        return  true;
    }

    private boolean checkCameraHardware(Context context)
    {

        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }
    private void toggleFrontBackCamera()
    {

    }
}

5.在布局文件里面添加

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CameraXDome">


    <TextureView
        android:id="@+id/view_camera"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />

    <ImageButton
        android:id="@+id/btn_takePict"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_camera"
        android:layout_marginBottom="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

    </ImageButton>

    <ImageButton
        android:id="@+id/btn_flash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_flash"
        android:layout_marginBottom="35dp"
        android:layout_marginStart="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent">
    </ImageButton>

    <ImageButton
        android:id="@+id/btn_switch_camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_switch_camera"
        android:layout_marginBottom="30dp"
        android:layout_marginStart="330dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent">
    </ImageButton>

</androidx.constraintlayout.widget.ConstraintLayout>

6.运行APP,因为模拟器没有前视摄像头,上真机调试就可以看到效果。
在这里插入图片描述

<think>好的,我现在需要帮助用户解决Java程序中无法打开摄像头的问题。首先,我得先理解用户的问题。用户提到在Java程序中打开摄像头时报错,想找到解决方案。根据用户提供的几个引用内容,看起来可能涉及到权限问题、HTTPS环境、硬件驱动或者信号干扰等因素。 首先,参考引用[1]和[2],Android平台和Chrome浏览器中摄像头访问问题可能与权限或安全协议有关。比如,Android可能需要正确的权限声明,而Web应用可能需要HTTPS环境。不过用户的问题是Java程序,可能需要区分是桌面应用还是Android应用?不过用户提到的引用里有Android相关的,所以可能用户的问题是关于AndroidJava程序? 不过用户的问题描述是“Java程序”,所以可能是桌面应用。这时候需要考虑Java访问摄像头的常见问题。Java中常用的库有OpenCV、JavaCV或者直接使用JMF(已过时)。比如引用[1]提到OpenCV在Android打开摄像头失败,可能涉及驱动或权限问题。引用[4]提到MIPI摄像头的信号干扰问题,需要调节驱动代码中的频率,这可能更底层,适用于嵌入式系统。 用户可能的情况可能有几种:1.权限问题,比如在Android中没有声明摄像头权限;2.驱动或硬件问题,比如摄像头驱动未正确安装或硬件故障;3.代码中的配置错误,比如参数设置不正确;4.在Web应用中,可能未使用HTTPS导致浏览器阻止访问;5.多线程或资源冲突,比如摄像头被其他程序占用。 接下来,我需要根据这些可能性逐一分析解决方案。首先,检查权限是否正确。如果是Android应用,需要在AndroidManifest.xml中添加摄像头权限。如果是桌面应用,可能需要安全策略文件或者用户授权。另外,引用[2]提到HTTPS的问题,如果Java程序是Web应用,可能需要确保使用安全协议,但如果是桌面应用,则可能不需要。 其次,检查摄像头是否被其他程序占用,导致无法访问。比如在Windows中,如果另一个软件正在使用摄像头Java程序可能无法打开它。需要确保摄像头未被占用。 然后,检查代码是否正确。比如使用OpenCV时,是否正确初始化摄像头设备,设备索引是否正确(比如0代表默认摄像头)。例如,引用[1]中的问题可能需要检查设备驱动或权限设置。 另外,硬件或驱动问题,可能需要更新摄像头驱动,或者检查硬件连接是否正常。引用[4]中的情况可能需要调整驱动中的频率设置,但这可能适用于特定硬件平台,如RK3588S。 此外,对于Android应用,可能需要设置合适的媒体录制参数,比如引用[3]中提到的视频编码比特率设置,错误的参数可能导致初始化失败。 总结可能的解决方案步骤: 1. 确保程序有访问摄像头的权限(如Android的权限声明,桌面应用的安全策略)。 2. 检查摄像头是否被其他程序占用,关闭可能冲突的软件。 3. 验证代码中摄像头初始化的参数是否正确,比如设备索引、格式设置等。 4. 如果是Web应用,确保使用HTTPS协议(参考引用[2])。 5. 更新或重新安装摄像头驱动程序,检查硬件连接。 6. 对于特定硬件平台,可能需要调整驱动设置,如信号频率(参考引用[4])。 7. 检查错误日志或异常信息,根据具体报错内容进行调试。 用户可能需要根据具体的报错信息来进一步排查问题。比如,如果报错是权限被拒绝,就需要检查权限设置;如果是设备无法打开,可能是索引错误或驱动问题。 最后,生成相关问题,帮助用户进一步理解和解决可能的相关问题。</think>### Java程序打开摄像头报错解决方案 在Java程序中无法打开摄像头的常见原因及解决方法如下: --- #### 1. **权限问题** - **场景**: 在Android或Web应用中,未正确声明摄像头权限会导致访问失败。 - **解决方案**: - **Android应用**:在`AndroidManifest.xml`中添加权限声明: ```xml <uses-permission android:name="android.permission.CAMERA" /> ``` 动态请求运行时权限(针对Android 6.0以上)[^1]。 - **桌面应用**:若使用安全管理器,需在策略文件中授予权限: ```java grant { permission java.security.AllPermission; }; ``` --- #### 2. **摄像头被占用或硬件问题** - **场景**: 摄像头被其他程序占用或硬件驱动异常。 - **解决方案**: - 关闭其他可能使用摄像头的程序(如视频会议软件)。 - 检查设备管理器(Windows/Linux)或系统日志,确认摄像头驱动正常。 - 尝试更换USB接口或重启设备(针对外接摄像头)。 --- #### 3. **代码配置错误** - **场景**: 使用OpenCV/JavaCV等库时,设备索引或参数设置错误。 - **解决方案**: ```java // 示例:OpenCV初始化摄像头 VideoCapture capture = new VideoCapture(0); // 0表示默认摄像头 if (!capture.isOpened()) { System.err.println("摄像头打开失败!"); } ``` - 确认设备索引正确(如尝试0, 1, 2等值)。 - 检查库的版本兼容性,更新至最新版本。 --- #### 4. **HTTPS环境要求(Web应用)** - **场景**: 浏览器要求通过HTTPS协议访问摄像头(如Chrome)[^2]。 - **解决方案**: - 部署服务端为HTTPS协议(如Tomcat配置SSL证书)。 - 本地测试可使用`https://localhost`或生成自签名证书。 --- #### 5. **信号干扰或驱动配置(嵌入式设备)** - **场景**: MIPI摄像头因信号干扰无法打开(如RK3588S开发板)[^4]。 - **解决方案**: - 修改摄像头驱动中的信号频率配置: ```c // 示例:调整ov13855摄像头驱动(Linux内核) sensor->lane_data[0].frequency = 1000; // 单位:MHz ``` - 联系硬件厂商获取适配参数。 --- #### 6. **错误日志分析** - **关键步骤**: 捕获异常信息以定位具体原因: ```java try { // 摄像头操作代码 } catch (Exception e) { e.printStackTrace(); // 输出详细错误 } ``` - 根据日志关键词(如`Permission denied`、`Device busy`)针对性解决。 ---
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知来者逆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值