从Android文件管理器获取错误的图像文件路径

时间:2015-11-20 13:17:04

标签: android android-intent android-imageview android-image android-file

在我的应用程序中,我想打开一个图像,并使用文件管理器将其“加载”到应用程序。我已经使用Intent.ACTION_GET_CONTENTonActivityResult()方法完成了操作。一切都很好,除了我得到的路径。它的格式很奇怪,我无法在ImageView

中显示图像
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            mFileManagerString = selectedImageUri.getPath();
            showPreviewDialog(mFileManagerString);
        }
}

此处mFileManagerString = /document/image:19552

当我调用方法在ImageView

中显示图像时
public void setPreviewIV(String pPath) {
        Bitmap bmImg = BitmapFactory.decodeFile(pPath);
        receiptPreviewIV.setImageBitmap(bmImg);
}

我收到以下错误:

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /document/image:19552: open failed: ENOENT (No such file or directory)

如何获取图片的正确路径,以便我可以在ImageView中显示它?

1 个答案:

答案 0 :(得分:1)

  

如何获得正确的图像路径

你已经拥有它。通过Uri参数传递给onActivityResult()的是Intent。仅从getPath()中拉出Uri毫无意义。这类似于认为/questions/33827687/wrong-image-file-path-obtained-from-android-file-manager是硬盘上的路径,只是因为您的Web浏览器显示包含该路径的URL。

此外,您当前的代码正在加载和解码主应用程序线程上的Bitmap。不要这样做,因为它在完成工作时会冻结UI。

我建议您使用众多image-loading libraries available for Android中的任何一个。所有体面的(例如毕加索,通用图像加载器)不仅需要Uri作为输入,而且还会在后台线程上为您加载图像,并将其应用到主应用程序上的ImageView仅在位图准备就绪时进行线程化。

如果出于某种原因,您认为自己必须自行执行此操作,请使用ContentResolver及其openInputStream()获取InputStream代表的数据Uri }。然后,将其传递给decodeStream()上的BitmapFactory。在后台线程中执行所有操作(例如,doInBackground()的{​​{1}}),然后将AsyncTask应用于主应用程序线程上的Bitmap(例如{ {1}}的{​​1}}。