【发布时间】:2016-09-20 17:06:08
【问题描述】:
注意:在下面的 SO 链接中提出了类似的问题,但没有一个 提议的解决方案对我有用,因此启动了这个线程。
- MediaStore.Images.Media.insertImage is returning null when trying to save the image
- Why Images.Media.insertImage return null
问题陈述: 我正在从 url 下载图像,然后尝试共享相同的图像。为此,我需要通过将图像保存在 MediaStore.Images.Media 中来获得的 Uri。
代码:
A.从 AsyncTask 类中获取下载的图像
public void processDownloadedImage(Bitmap bitmap) {
if (bitmap == null) {
Toast.makeText(this,"Image could not be downloaded and shared!",Toast.LENGTH_LONG).show();
}
else {
downloadedImage = bitmap;
checkPermissionShowShareSheet();
}
}
B.检查 Marshmallow 及更高版本的权限
public void checkPermissionShowShareSheet() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)){
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},2909);
}
else {
updateImageUri(downloadedImage);
showShareSheet(downloadedImageUri);
}
}
else {
updateImageUri(downloadedImage);
showShareSheet(downloadedImageUri);
}
}
C.获取图片Uri
private void updateImageUri(Bitmap inImage){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
fixMediaDir();
String path = MediaStore.Images.Media.insertImage(this.getContentResolver(), inImage, "SomeImage", null);
storePathInSharedPreferences(path);
Uri uri = Uri.parse(path);
downloadedImageUri = uri;
}
void fixMediaDir() {
File sdcard = Environment.getExternalStorageDirectory();
if (sdcard != null) {
File mediaDir = new File(sdcard, "DCIM/Camera");
if (!mediaDir.exists()) {
mediaDir.mkdirs();
}
}
}
D.清单文件使用权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
问题:下一行返回的值为空
String path = MediaStore.Images.Media.insertImage(this.getContentResolver(), inImage, "SomeImage", null);
有什么想法吗?
这是 Stackbacktrace 的一部分:
Failed to insert image java.io.FileNotFoundException: No such file or directory
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
at android.content.ContentProviderProxy.openAssetFile(ContentProviderNative.java:620)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:939)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:686)
at android.content.ContentResolver.openOutputStream(ContentResolver.java:662)
at android.provider.MediaStore$Images$Media.insertImage(MediaStore.java:934)
at myorg.myapp.ImageDescription.updateImageUri(ImageDescription.java:165)
【问题讨论】:
标签: android image uri mediastore