Android拍照上传

引言

在移动应用开发中,拍照上传是一个常见的功能需求。用户可以通过拍照来捕捉照片,然后将照片上传到服务器或者存储到本地。Android平台提供了丰富的API来实现这个功能,本文将介绍如何在Android应用中使用相机拍照并上传照片。

准备工作

在开始之前,我们需要进行一些准备工作。

添加权限

首先,我们需要在AndroidManifest.xml文件中添加相机和存储权限。

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

创建文件提供器

由于Android 7.0及以上版本限制了文件的访问权限,我们需要创建一个文件提供器来为相机应用提供访问存储的权限。

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

接下来,我们需要在res/xml目录下创建一个file_paths.xml文件,并添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="
    <external-path name="my_images" path="Android/data/${applicationId}/files/Pictures" />
</paths>

拍照功能实现

现在我们来实现拍照功能。

创建一个布局文件

首先,我们需要创建一个布局文件来显示拍照按钮和预览图片的ImageView。

<LinearLayout xmlns:android="
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button_capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="拍照" />

    <ImageView
        android:id="@+id/image_preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />
</LinearLayout>

编写Java代码

接下来,我们需要编写Java代码来处理拍照逻辑。

首先,我们需要定义一些成员变量。

private static final int REQUEST_IMAGE_CAPTURE = 1;
private String currentPhotoPath;
private ImageView imageView;

然后,在Activity的onCreate方法中,初始化布局和按钮的点击事件。

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

    Button captureButton = findViewById(R.id.button_capture);
    imageView = findViewById(R.id.image_preview);

    captureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dispatchTakePictureIntent();
        }
    });
}

接下来,我们需要实现dispatchTakePictureIntent方法来启动相机应用。

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            ex.printStackTrace();
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

在createImageFile方法中,我们创建一个临时文件来保存拍照的照片。

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).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
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

最后,我们需要处理拍照完成后的结果,在onActivityResult方法中,我们可以