![](/img/trans.png)
[英]FileNotFoundException when trying to download a image from web
[英]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;
解码文件返回在这里抛出一个 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 沙箱中。 您需要将它作为资源添加到应用程序中,然后作为资源而不是文件访问它。
如果您尝试访问网络图像,则需要先下载它。 Web 图像“ http://example.com/example.jpg ”的 AbsolutePath 将是“/example.jpg”,当您尝试打开它时,这对您没有多大好处。
使用decodeStream
而不是decodeFile
。
使用getContentResolver().openInputStream(myUri)
打开流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.