如何在Android 10上拍照并将结果保存为照片?
谷歌在Android 10上引入了作用域存储,根据文档,我们可以使用MediaStore API在不请求许可的情况下写入公共目录 在Android 10之前,当我们需要拍摄照片并将其保存为图片时,代码如下所示:如何在Android 10上拍照并将结果保存为照片?,android,mediastore,android-10.0,scoped-storage,Android,Mediastore,Android 10.0,Scoped Storage,谷歌在Android 10上引入了作用域存储,根据文档,我们可以使用MediaStore API在不请求许可的情况下写入公共目录 在Android 10之前,当我们需要拍摄照片并将其保存为图片时,代码如下所示: private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there
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
...
}
// 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);
}
}
}
String currentPhotoPath;
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 = Environment.getExternalStoragePublicDirectory(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;
}
我们直接在图片中创建文件,并将文件uri放入takePhotoIntent extra,当我们启动intent并拍摄照片时,原始大小的照片将保存到Pictures目录中
但现在我们的目标是安卓10,据文件称,没有必要请求WRITE_EXTERNAL_存储权限将照片保存到图片目录中
如果没有权限,我们无法创建文件,然后获取文件的uri,将其放入intent extra。那么我们如何保存原始大小的照片呢?“那么我们如何保存原始大小的照片呢?”——如果您将
文件(和文件提供程序XML)更改为可以写入的位置(例如上下文上的getExternalFilesDir()
),那么您的代码就可以了。或者,至少在原则上,您可以使用MediaStore
上的insert()
获取Uri
,然后通过EXTRA\u OUTPUT
将该Uri
传递到相机应用程序。我们直接在图片中创建文件
不要在那里创建空文件。如果用户取消拍照,则留下一个空文件。您只需要在图片目录中找到文件的路径。使用过的摄像头应用程序将创建该文件。