java Android编程存储的图像在PC上的格式无效
我正在尝试拍摄一张照片,并在Android Documentation之后保存它
主要区别在于我的代码是扩展Fragment
,而不是Activity
。事实上,我将图片存储在私人应用文件夹中,而不是公共外部存储
我的代码:
private void dispatchTakePictureIntent() {
PackageManager packageManager = getActivity().getPackageManager();
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(packageManager) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Log.d(TAG, "Error occurred while creating the File:"+ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.eric.nativetoolkit.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
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 = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpeg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
这基本上是因为每次我尝试在外部存储器上保存图片时,AndroidStudio logcat都会显示错误“创建文件时出错”。由于权限,我在AndroidManifest中有以下权限。xml,我也有一个方法来请求它,但没有任何效果
AndroidManifest。xml:
<manifest xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
package="com.eric.nativetoolkit">
<uses-permission 安卓:name="安卓.permission.WRITE_EXTERNAL_STORAGE"
安卓:maxSdkVersion="18" />
<application
安卓:allowBackup="true"
安卓:supportsRtl="true">
<provider
安卓:name="安卓x.core.content.FileProvider"
安卓:authorities="com.eric.nativetoolkit.fileprovider"
安卓:exported="false"
安卓:grantUriPermissions="true">
<meta-data
安卓:name="安卓.support.FILE_PROVIDER_PATHS"
安卓:resource="@xml/file_paths" />
</provider>
</application>
</manifest>
文件路径。xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:安卓="http://schemas.安卓.com/apk/res/安卓">
<external-files-path name="my_images" path="." />
</paths>
但是,主要问题是,即使将图片正确地存储在我的包/文件/图片目录中,当我尝试查看图像时,将我的设备插入计算机并导航到文件夹,它也会显示消息(西班牙语)“无法打开文件”:
我不明白的是,为什么在我的设备中我可以正确地显示图像。我尝试过改变格式(JPG,JPEG,PNG…)但没有区别
# 1 楼答案
您正在通过
ACTION_IMAGE_CAPTURE
启动第三方相机应用程序。它无权写入FileProvider
提供的Uri
指定的位置。添加FLAG_GRANT_WRITE_URI_PERMISSION
会告诉Android,你的应用程序希望将对该位置的写访问权限授予相机应用程序如果没有该许可,摄像头应用程序将因某种错误而失败。您仍然会有一个文件,因为在尝试
ACTION_IMAGE_CAPTURE
之前,您正在使用File.createTempFile()
创建一个不必要的空文件。如果通过桌面文件管理器查看文件大小,应该会看到它是0字节。0字节的文件不是有效的图像,这就是桌面无法显示它的原因