【问题标题】:Cant save image to gallery无法将图像保存到图库
【发布时间】:2019-09-27 23:57:28
【问题描述】:

我正在尝试使用 MediaStore 将位图作为图像保存到手机存储中,如下所示:

 MediaStore.Images.Media.insertImage(contentResolver, bitmap, "title" , "description")

图像没有保存在设备存储中,我已经检查了模拟器和物理设备。


到目前为止我做了什么:

  • 检查了我传递的位图是我想要的位图:

    为此,我在调试器的帮助下检查了它的值,如下所示:

    1) 在应该保存图像的行上放置一个断点并检查我正在传递的位图,该位图与我要保存的位图相同:

    2) 位图如下所示:

  • 确保用户已授予将文件写入外部存储(以下行)的权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

  • 确保图像未保存在图库末尾或设备存储空间内的任何其他位置


我知道我可能不使用 this thread 中提到的 MediaStore 就可以保存图像,但我想知道我在这里做错了什么以及为什么我不能将位图保存为设备存储中的图像。

【问题讨论】:

  • insertImage 返回什么?您在 logcat 中是否有任何带有MediaStore 标签的日志?
  • @esentsov 我没有找到任何使用 MediaStore 的日志,但这是个好主意。我刚刚检查了insertImage 做了什么,我发现了这个 @return 新创建图像的 URL,如果图像因任何原因无法存储 *,则为 null
  • 我的意思是它在您的代码中返回的内容。它返回 null 吗?
  • @esentsov 感谢您的帮助。我设法解决了这个问题,如果您想稍后检查,我会写答案

标签: android bitmap android-storage


【解决方案1】:

我试过了,但也没有为我工作。所以我用了安卓下载管理器,很简单;-)

这里是代码

/*
This method can be used to download an image from the internet using a url in Android. This use Android Download Manager to
download the file and added it to the Gallery. Downloaded image will be saved to "Pictures"
Folder in your internal storage
*/

private void downloadImageNew(String filename, String downloadUrlOfImage){
    try{
        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Uri downloadUri = Uri.parse(downloadUrlOfImage);
        DownloadManager.Request request = new DownloadManager.Request(downloadUri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false)
                .setTitle(filename)
                .setMimeType("image/jpeg") // Your file type. You can use this code to download other file types also.
                .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,File.separator + filename + ".jpg");
        dm.enqueue(request);
        Toast.makeText(this, "Image download started.", Toast.LENGTH_SHORT).show();
    }catch (Exception e){
        Toast.makeText(this, "Image download failed.", Toast.LENGTH_SHORT).show();
    }
}

【讨论】:

    【解决方案2】:

    由于某种原因,即使在授予 WRITE_EXTERNAL_STORAGE 之后,在查看了一些日志后,我注意到我收到了这个错误:

    Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=11218, uid=10079 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()
    

    这对我来说看起来很奇怪,因为我在将图像保存到图库之前检查了此权限是否已获得。

    解决这个问题的方法是删除应用并重新安装

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多