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

Wrong image file path obtained from Android file manager

在我的应用程序中,我想打开一个图像,然后 "load" 使用文件管理器将其发送到应用程序。我已经使用 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 中显示它?

How to get the proper path to the image

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

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

我建议您使用众多 image-loading libraries available for Android 中的任何一种。所有体面的(例如,Picasso,Universal Image Loader)不仅将 Uri 作为输入,还会在后台线程上为您加载图像,将其应用到主应用程序上的 ImageView仅当位图准备就绪时才线程。

如果出于某种原因,您觉得必须自己执行此操作,请使用 ContentResolver 及其 openInputStream() 为 [= 表示的数据获取 InputStream 10=]。然后,将其传递给 BitmapFactory 上的 decodeStream()。在后台线程中执行所有这些操作(例如 AsyncTaskdoInBackground()),然后将 Bitmap 应用到主应用程序线程上的 ImageView(例如 onPostExecute()AsyncTask).