安卓:使用 uri 或文件路径解码位图时找不到文件



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

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

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

  • 在模型中存储file.getabsolutePath()而不是uri.toString。这会将 uriString 格式更改为file:/foo/bar,但仍然不起作用
  • 呼叫Uri.parse(uriString).getPath()
  • uriString创建一个新的 File 对象并调用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)

如前所述,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()

最新更新