Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/212.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android:FileNotFoundException尝试从Uri获取图像时_Java_Android_Bitmap_Uri_Filenotfoundexception - Fatal编程技术网

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

Java Android:FileNotFoundException尝试从Uri获取图像时,java,android,bitmap,uri,filenotfoundexception,Java,Android,Bitmap,Uri,Filenotfoundexception,我试图得到一个图像的宽度和高度,以便在显示之前对其进行重新缩放,以防图像太大。我的方法接收图像的uri,但在尝试使用BitmapFactory对其进行解码时,我总是得到一个FileNotFoundException 以下是我的代码示例: Uri myUri; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapF

我试图得到一个图像的宽度和高度,以便在显示之前对其进行重新缩放,以防图像太大。我的方法接收图像的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;
解码文件返回在此处抛出FileNotFoundException。但是,我仍然可以使用uri显示图像,而无需使用位图工厂:

        Uri myUri;

        Bitmap myBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), myUri);
此代码的问题在于,使用大图像时,返回的位图可能会导致OutOfMemory错误

调试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沙箱中。您需要将其作为资源添加到应用程序中,然后将其作为资源而不是文件进行访问


如果您试图访问web映像,则需要先下载它。web图像“”的绝对路径为“/example.jpg”,当您尝试打开它时,这对您没有多大好处。

使用
decodeStream
而不是
decodeFile


getContentResolver().openInputStream(myUri)

打开流自从我玩Android已经有一段时间了,但是由于它是一个FileNotFoundException,您是否尝试过检查“new File(myUri.getPath()).getAbsolutePath()”以查看返回的确切值?可能有一些奇怪的事情发生了。需要更多关于myUri的信息。我不知道是什么content://com.android.providers.media.documents/document/image%3A20472 我在实际的android设备上测试,而不是在沙箱上。为了提供更多的上下文,要求用户从他的设备中选择一张图片。在用户选择图片后调用的方法“onActivityResult”中,uri是使用作为参数传递的Intent中的数据创建的。uri的定义如下:public void onActivityResult(int requestCode,int resultCode,Intent data){uri myUri=data.getData();…}这确实是个问题,谢谢。我已经更新了问题,给出了结果代码。