【问题标题】:Android: file not found when decoding bitmap with uri or filepathAndroid:使用uri或文件路径解码位图时找不到文件
【发布时间】:2016-11-24 16:13:51
【问题描述】:

我的应用程序允许用户使用外部相机活动拍照作为某些数据收集的一部分,并将生成的文件路径的 Uri.toString() 存储在模型中以供以后使用。

稍后在回收站视图中查看集合时,由于加载的图像的大小,应用程序会变慢,因此我实现了 Google 的解决方案 here,但是我在堆栈跟踪中得到了 FileNotFoundExceptions,并且图像未加载。视图的其余部分加载正常,应用没有崩溃。

如前所述,uriStringcontent:foo/bar 格式的字符串。我尝试过的解决方案包括。

  • 在模型中存储file.getabsolutePath() 而不是uri.toString。这会将 uriString 格式更改为 file:/foo/bar,但仍然不起作用
  • 致电Uri.parse(uriString).getPath()
  • uriString 创建一个新的文件对象,并从中调用getAbsolutePath()getPath()

需要明确的是,调用imageView.setImageURI(Uri.parse(this.item.getPhotoURI())); 绝对有效。所以文件存在并且 uriString 可以被 Android 解释。有问题的功能如下。下面是我的堆栈跟踪。

private Bitmap decodeSampledBitmapFromFile(String uriString, int reqWidth, int reqHeight)
    {

        // First we do this just to check dimensions (apparently)
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;


        BitmapFactory.decodeFile(uriString, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // And then return with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(uriString, options);

    }

还有我的堆栈跟踪:

11-24 16:10:57.762 17199-17199/uk.mrshll.matt.accountabilityscrapbook E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: file:/storage/emulated/0/Android/data/uk.mrshll.matt.accountabilityscrapbook/files/Pictures/JPEG_20161124_160913_-1155698030.jpg: open failed: ENOENT (No such file or directory)

【问题讨论】:

  • 文件名可能是问题所在。 JPEG_20161124_160913_-1155698030.jpg 注意 11556...0 开头之前的破折号,尽量避免在文件名的任何地方使用破折号。

标签: android path bitmapfactory


【解决方案1】:

如前所述,uriString 是格式为 content:foo/bar 的字符串。

不是根据你的错误。您的错误表明您正在尝试将"file:/storage/emulated/0/Android/data/uk.mrshll.matt.accountabilityscrapbook/files/Pictures/JPEG_20161124_160913_-1155698030.jpg" 传递给decodeFile()。该字符串上表示的方案是file,而不是content。更重要的是,decodeFile() 不采用Uri(或Uri 的字符串表示),而是采用文件路径,并且文件路径没有方案。

如果您希望混合使用 contentfile 方案:

  • 坚持Uri(或者,最坏的情况,从字符串中重新解析Uri
  • 使用ContentResolveropenInputStream()Uri表示的内容上获得InputStream(因为openInputStream()同时支持contentfile方案)
  • 使用decodeStream() 代替decodeFile()

【讨论】:

  • 对不起。这是一个不同的堆栈跟踪,正如我的帖子中提到的,我尝试换掉 urlString 的创建方式。尝试您对 ContentResolver 的建议
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
相关资源
最近更新 更多