android - 如何拍照并将结果保存到 Andrdoid 10 上的图片中?
问题描述
谷歌在 Android 10 上引入了 Scoped Storage,根据文档,我们可以使用 MediaStore API 在不请求权限的情况下写入公共目录。
在Android 10之前,当我们需要拍照并保存到Pictures时,代码如下:
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;
}
我们直接在 Pictures 中创建文件,并将文件 uri 放入 takePhotoIntent extra 中,当我们启动意图并拍照时,原始大小的照片将保存到 Pictures 目录中。
但是现在我们的目标是 android 10,根据文档,请求 WRITE_EXTERNAL_STORAGE 权限将照片保存到图片目录中是不必要的。
没有权限,我们不能创建文件然后获取文件的uri,将其放入intent extra。那么我们如何保存原始尺寸的照片呢?
解决方案
推荐阅读
- c - PC2 中的运行时错误,但在 Dev-C++ 中有效
- haskell - 使用 >>= 将表达式转换为 do 表示法
- angular - ngIf 在 BSDropdown 上
- javascript - 从 bpmn Moodle 中的异步函数中检索对象
- python - 通过服务更换壁纸的问题
- bixby - 在 Bixby 模拟器中,是否可以在开发配置和生产配置之间切换?
- php - 当值为真时,PHP if else 语句不执行代码
- javascript - 如何将对象从视图传递到 ASP.NET MVC 中的控制器?
- javascript - 将输入数据从子级传递给父级 React.js
- python - 包括函数的循环,因此如果数字不正确,它可以要求用户重新输入数字