首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Android:从相机获取文件名?

在Android系统中,从相机获取文件名可以通过以下步骤实现:

  1. 首先,在AndroidManifest.xml文件中添加相机和外部存储访问权限:
代码语言: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" />
  1. 在代码中创建一个File对象,用于存储拍照后的图片:
代码语言:java
复制
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  // prefix
        ".jpg",         // suffix
        storageDir      // directory
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}
  1. 在代码中启动相机应用,并将拍照后的图片保存到上一步创建的File对象中:
代码语言:java
复制
private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            // Handle the exception appropriately in your application
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                                                      "com.example.android.fileprovider",
                                                      photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}
  1. 在onActivityResult方法中处理拍照后的结果,并获取文件名:
代码语言:java
复制
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
        // Get the file name of the captured image
        String fileName = new File(mCurrentPhotoPath).getName();
        // Do something with the file name
    }
}

通过以上步骤,您可以在Android系统中从相机获取文件名。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券