我正在尝试从 Fragment
拍照后获取完整图像。
如果我使用文件中的 Uri (Uri.fromFile(file)
),拍照并点击“确定”按钮后相机不会退出(看起来可以t 写信给 Uri 或者谁知道呢)。
使用File
String
,格式为'/data/data/com.package.bla/cache/img198346262jpg'
,它不能正常工作(文件在那里,但它是空的,因为相机没有在上面保存任何东西)。
到目前为止我尝试了什么:
- 创建后删除文件,如this example做。但是,相机退出后该文件不存在。
- 添加了外部存储读取权限,以防万一
所以我不知道为什么图像没有被保存并且已经花费/浪费了很多时间来测试和弄清楚为什么它不工作。
fragment :
private void launchCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File outputDir = getActivity().getCacheDir();
File file = null;
try {
file = File.createTempFile("img", "jpg", outputDir);
} catch (IOException e) {
e.printStackTrace();
}
if (file != null) {
mImageUri = Uri.fromFile(file); //using Uri is not even exiting the camera
//mImageUri = File.toString(); //If I use String instead of an Uri, it works better (ie, can accept camera photo)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(cameraIntent, RESULT_TAKE_IMAGE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
Bitmap original = BitmapFactory.decodeFile(mImageUri.toString(), bounds);
}
}
编辑的代码,mImageUri。如前所述,如果我使用 Uri,我什至无法接受相机应用程序中的照片。使用字符串可以让我接受照片,尽管照片实际上并没有保存(即文件里面有 0 个字节)。
解释:问题与保存到缓存目录有关。也许这是一个错误,我缺少权限,或者相机应用程序无法保存到您的应用程序私有(private)数据目录中。添加权限 FLAG_GRANT_WRITE_URI_PERMISSION 并没有解决它。相关帖子:Store image from camera into private app cache directory和 Saving camera data to cache when launched via intent
UPDATE 从 Android 2.2 开始,可以使用 getExternalCacheDir()
方法代替 getCacheDir()
最佳答案
来自 android 26+ 的 Uri.fromFile 将不起作用,您应该改用 File 提供程序。
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
.........
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
</application>
res/xml/file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
</paths>
终于
final Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// output file
File path = new File(Environment.getExternalStorageDirectory(), "tmp.mp4");
// com.mydomain.fileprovider is authorities (manifest)
// getUri from file
Uri uri = FileProvider.getUriForFile(this, "com.mydomain.fileprovider", path);
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(takeVideoIntent, 99);
在 android 8.0 和 5.1.1 上测试
更新:某些设备的内置摄像头不支持 EXTRA_OUTPUT,因此如果您想在所有设备上工作,请构建自己的摄像头模块。
关于android - 使用 Cache Uri 作为 MediaStore.EXTRA_OUTPUT 时相机无法工作/保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18711525/