📜  在android中点击相机获取图像-Java(1)

📅  最后修改于: 2023-12-03 15:37:34.243000             🧑  作者: Mango

在 Android 中点击相机获取图像 - Java

在 Android 中,我们可以使用系统相机获取图像。本文将介绍如何在 Android 应用程序中实现点击相机来获取图像的功能。

步骤:
1. 添加相机权限

AndroidManifest.xml 中添加以下代码来获取相机权限:

<uses-permission android:name="android.permission.CAMERA" />
2. 创建相机 Intent

在需要调用相机的地方创建相机 Intent:

private static final int REQUEST_IMAGE_CAPTURE = 1;

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}
3. 处理相机返回的图像

当用户拍完照片并返回应用程序时,在调用相机 Intent 的 onActivityResult 方法中处理图像:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        // Do something with the imageBitmap
    }
}

注意:返回的图像存储在 Intent 的 extras 中。在本示例中,我们使用 Bitmap 对象来保存图像。

4. 在 Android 7.0 及以上版本中正确处理文件 URI

如果您的应用程序针对 Android 7.0 及更高版本进行了编译,则根据应用安全性建议的建议,您需要注意文件 URI 的处理方式。

AndroidManifest.xml 中添加以下代码以声明 FileProvider

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.your.package.name.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 文件,内容如下:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Pictures" />
</paths>

然后,在需要调用相机的地方创建一个 File 对象和相机 Intent,如下所示:

private static final int REQUEST_IMAGE_CAPTURE = 1;
private String mCurrentPhotoPath;

private File createImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,
        ".jpg",
        storageDir
    );
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    "com.your.package.name.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

onActivityResult 方法中,您可以通过 mCurrentPhotoPath 访问文件的路径,如下所示:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        // Get the dimensions of the View
        int targetW = mImageView.getWidth();
        int targetH = mImageView.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        mImageView.setImageBitmap(imageBitmap);
    }
}
结论

这是在 Android 应用程序中点击相机获取图像的简单示例。希望这篇文章可以帮助您了解如何在您的应用程序中实现该功能。