Android:尝试从 Uri 获取图像时出现 FileNotFoundException

Android : FileNotFoundException when trying to get an image from Uri

我正在尝试获取图像的宽度和高度,以便在显示之前调整它的大小以防它太大。我的方法接收图像的 uri,但在尝试使用 BitmapFactory 对其进行解码时,我总是得到 FileNotFoundException。

这是我的代码示例:

    Uri myUri;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(new File(myUri.getPath()).getAbsolutePath(), options);

    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;

Decode File returns 在此处抛出 FileNotFoundException。但是,我仍然可以使用 uri 显示图像,而无需使用位图工厂:

        Uri myUri;

        Bitmap myBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), myUri);

此代码的问题是返回的位图在使用大图像时可能会导致 OutofMemoryError。

当我调试我的 Uri 时,我得到这个:

content://com.android.providers.media.documents/document/image%3A20472

更新 ||这是工作代码

    Uri myUri;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    // This is the part that changed
    InputStream inputStream = context.getApplicationContext().getContentResolver().openInputStream(myUri);
    BitmapFactory.decodeStream(inputStream,new Rect(),options);

    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;

所有这些当然都被 try/catch 包围了。

研究了一段时间后,我认为问题可能是图像文件确实不存在。

如果您尝试访问计算机上的本地文件,该文件将不在 Android 沙盒中,应用程序实际上是 运行。您需要将其作为资源添加到应用程序,然后将其作为资源而不是文件进行访问。

如果您尝试访问网络图像,您需要先下载它。网络图像“http://example.com/example.jpg”的绝对路径将是“/example.jpg”,当您尝试打开它时,这对您没有多大帮助。

使用 decodeStream 而不是 decodeFile

使用 getContentResolver().openInputStream(myUri) 打开流。